0

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?

Harry Stout
  • 145
  • 1
  • 8
  • 2
    My money is on `printf("Child is running\n"); fflush(stdout); while(1);`. – Lundin Jan 28 '22 at 13:47
  • Yeah, that seems to produce the result I was expecting! Can you offer any insight as to what is going on under the hood here? Why wouldn't printf just print straight to stdout? – Harry Stout Jan 28 '22 at 13:58
  • 1
    In many environments it wouldn't make a difference. In many environments printing `\n` is as good as a `fflush(stdout)`. (That's why Darth-CodeX reported no difference in their answer.) But it sounds like your environment (minix?) is different in that respect. – Steve Summit Jan 28 '22 at 14:03
  • 1
    @HarryStout In that case, please check the linked duplicate. Basically the phenomenon is called "line buffering", but sending a `\n` doesn't necessarily flush the stdout buffer on some systems. – Lundin Jan 28 '22 at 14:05

1 Answers1

0

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.

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23