It is an academic question so the reason is to understand the output.
I have a code:
int main(int argc, char **argv) {
int k ;
while(*(++argv)) {
k = fork();
printf("%s ",*argv);
}
return 0;
}
running the program with : prog a b
The output is :
a b a b a b a b
Why do I get this result?
As suggested by Chris Lutz in the comments, you are observing the effect of a static buffer used by
printfbeing duplicated by thefork()call. The two processes created by the firstfork()do not printb(as you could expect, and as happens if you force a flush). They both printa bbecause they both have a pending, unflushedain their respective buffers.There are 4 processes (2^2, including the initial one), they all only really print at exit when the buffer is flushed, and they all have
a bin their respective buffers at that time.