Reputation: 341
I am trying to understand the following code:
int main(int argc, char **argv)
{
int pid1,pid2;
if((pid1=fork())<0)
{
printf("Error bla bla");exit(1);
}
else printf("A");
if((pid2=fork())<0)
{
printf("Error bla bla");exit(2);
}
if(pid1==0)printf("B\n");
if(pid2==0)printf("C\n");
exit(0);
return 0;
}
the output I get looks like this :
A
AC
AB
AB
C
If I change the first print to printf("A\n");
the output is
A
C
A
B
B
C
How do the processes behave in this situation ? I know that the second fork()
gets executed in both the parent process and the first child process but why does the output look like this ?
Also, why does it print the last 3 letters in that specific order ?
Upvotes: 0
Views: 100
Reputation: 1176
First of all, I believe the result of this sequence is not well defined - it's up to the implementor of printf() and the vagaries of process scheduling.
In general, printf() accumulates characters in a buffer, and prints them when it wants to - except that generally the presence of a newline '\n' triggers immediate printing.
If the process forks with characters still in the printf() buffer, both the parent and the child process will eventually print those characters. You fork twice, resulting in 4 processes. I'll call the original process G(randparent). G creates P(arent) at the first fork. P has pid1 == 0. Next each process forks again. Let's say G creates A(unt) and P creates C(hild). A and C have pid2 == 0. C also has pid1 == 0.
All of them have either printed the original A\n, or have A in their printf buffer.
Those with pid1 == 0 then printf B\n. If there's still an A in the buffer, it comes out as AB\n Those with pid2 == 0 then print C\n
So the sequence is
G: A(\n)
P: A(\n)B\n
A: A(\n)C\n
C: A(\n)B\nC\n
The order in which G,P,A, and C run is indeterminate. But the output of any given process appears in the order it's printf()d. It may be interlaced with output from other processes.
If A is printed with \n, then remove A(\n) from all the sequences except the grandparent.
Upvotes: 1
Reputation: 7482
Probable cause of your confusion is that the output of printf("A");
is not actually written on the terminal at the moment of the second fork. It is in a memory buffer and as such it is duplicated together with the rest of the process.
Upvotes: 0