>Here is my simple program:
> int i=0;
A child process is created here. So there are 2 processes running now.
The variable 'i' is copied from parent to child (as the child gets a
copy of parent's
stack space as part of fork call).
Each process is supposed to print the value of i (= 0) onto the standard
But it defers this as the buffer is not yet flushed. (Note here that
library is buffered, where as *write* API is not buffered.)
So there are 2 "0"s outstanding in the standard output buffer waiting to be
Now both the processes (the parent and the child process) calls fork each.
So there are 4 processes at this point. (Note, however, that the order of
creation of the child processes is undefined here).
In the process of creating 2 child processes, the parent's data space is
to the their respective child processes. If you remember, there were 2
before this each with a "0" in its standard output buffer. So this
buffer is also
copied as such to the child processes as mentioned earlier.
There are 4 "0"s in the standard output buffer altogether at this point
all the four processes reach this point). They are not yet in the standard
Before the program ends, the operating system flushes all the open
buffers on behalf
of the terminating processes. So the 4 outstanding "0" from 4 processes
to the standard output. Now the output is "0000".
Hope that was clear.
To, however, get the output as just "00", change the printf as:
I think you can realise what happens with the "\n" after the explanation
that went above!!
or use the following line instead of printf:
write(1 /* stdout */, "0", 1);
>I was expecting the output of this program to be 00( i.e. 2 zeros).
>But actual ouput on running this program is 0000(i.e. 4 zeros).[ I ran this
>on Linux 7.0 s/m with gcc compiler].
>Can some one explain why this is so? step by step explaination will be very
>Thanks in advance,