i think i know what's going on....it need to be something like this
复制内容到剪贴板
代码:
pid1 =fork();
if (pid1==0)//child1 process
{
sleep(3);
printf("Hello from Child1 Process %d.\n",getpid());
}
else //parent process
{
pid2 =fork();
if (pid2 == 0) //child2 process
{ sleep(3);
printf("Hello from Child2 Process %d.\n",getpid());
}
else //parent process
{
tprintf("Parent forked child1 process %d.\n", pid1);
sleep(1);
tprintf("Parent forked child2 process %d.\n", pid2);
sleep(1);
tprintf("Parent is waiting for child to exit.\n");
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
tprintf("child has exited.\n");
tprintf("Parent had exited.\n");
}
}because after you fork pid1, you didn't check the status immediately, that means both child and parent process will call fork for pid2
that is
parent ----fork pid1----fork pid2---print (Parent forked child1 process )
pid1 --------fork pid2---print(Hello from Child1 Process )
pid2(from parent) ----(here we got pid1!=0, so we go to Hello from Child2 process)
pid2(from pid1)------(here we inherite the status with pid1 process, that means variable pid1 is 0!!!, so we go to "Hello from Child1 Process ")
so in reality there are 2 pid2, but the pid2 from pid1 will display Hello from Child1 Process, because it inherite the status of pid1 process, so that pid1 variable became 0 when checking it....
[
本帖最后由 wangzhonnew 于 2008-4-7 03:12 编辑 ]