I am using the following code for a fork execution
#include <stdio.h>
#include <sys/types.h>
int main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("\n child 1");
pid=f开发者_开发知识库ork();
if (pid==0)
printf("\n child 2");
}
return 0;
}
The output I assume should be child1 child2
Instead I am getting
child1 child2 child1
Cannot understand the fork behaviour
If you have written data to any stdio FILE
before calling fork
and intend to use the same FILE
after fork
, you must call fflush
on that FILE
before calling fork
. Failure to do so results in undefined behavior.
See here for the formal requirements:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_05_01
Specifically,
Note that after a fork(), two handles exist where one existed before. The application shall ensure that, if both handles can ever be accessed, they are both in a state where the other could become the active handle first. The application shall prepare for a fork() exactly as if it were a change of active handle. (If the only action performed by one of the processes is one of the exec functions or _exit() (not exit()), the handle is never accessed in that process.)
You need to flush stdout:
printf( "\n child 1" )
fflush( stdout );
精彩评论