LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Strange behaviour of fork call in Linux (https://www.linuxquestions.org/questions/programming-9/strange-behaviour-of-fork-call-in-linux-45098/)

Uzair 02-12-2003 12:33 PM

Strange behaviour of fork call in Linux
 
Hi all,
I cannot understand why there is a difference in output of the following 2 programs, can any one help?

int main(void)
{
fork();
printf("Hello\n");
fork();
}

The above program prints Hello two times.

int main(void)
{
fork();
printf("Hello");
fork();
}

The above program (i.e. without "\n" in the printf) prints Hello 4 times....
Please help me in understanding this difference , I shall be grateful.

Thank you,
Uzair

llama_meme 02-12-2003 01:37 PM

It's something to do with the way stdio.h works (it does some quite complicated buffering and stuff behind the scenes, which would be sensitive to newlines, which might cause a buffer to be flushed or something).

If you replace the call to printf with one to write, like so:
Code:

write(1, "Hello\n", 6);
/* OR */
write(1, "Hello", 5);

Both versions output Hello twice.

Alex


All times are GMT -5. The time now is 10:04 AM.