Printf statement is being ignored if a while loop succeeds it

193 Views Asked by At

Here is my code:

int main(int arg, char *argv[]){
    short pid;
    if((pid = fork()) == 0){
        printf("Child is running\n");
        while(1) ;
    } else {
        printf("Parent is running\n");
    }
}

After running this, only "Parent is running" is printed to the console. If I remove the while loop, both statements are printed to the console. Why is the while loop causing the child's print statement to be ignored if it appears before it?

1

There are 1 best solutions below

0
Darth-CodeX On

In my case both statements were printing on stdout. I'm using Arch Linux

[tushar@arch Desktop]$ ./main
Parent is running
Child is running

In my case while(1); is being ignored, even after removing that line output is same as mentioned above.

After printing "Parent is running" to the stdout your program exits, and after that "Child is running" is printed to stdout.

I would suggest you to read this article fork() in c. Also use fflush(stdout); By the way I have never used minix.