【发布时间】:2012-02-20 12:09:41
【问题描述】:
我有这个 fork() 的例子,我需要做一个跟踪!
#include <unistd.h>
int main(void) {
int i;
for (i=0; i<3; i++)
if (fork())
wait(NULL);
return 0;
}
我的跟踪解决方案是,出了点问题,我不知道如何进行跟踪:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
int i,pid;
for(i=0;i<3;i++) {
pid=fork();
if(pid>0) ///if is father (true)
printf("PID After the fork child === %d & father === %d (i = %d) \n\n",(int)getpid,(int)getppid,i);
wait(NULL);
printf(" After the wait child=== %d & father=== %d (i = %d)|||\n",(int)getpid,(int)getppid,i);
}
}
这是我在终端中得到的。我可以清楚地看到它是不正确的,但我不知道如何解决这个问题:
PID After the fork child === 134513568 & father === 134513632 (i = 0)
After the wait child=== 134513568 & father=== 134513632 (i = 0)|||
PID After the fork child === 134513568 & father === 134513632 (i = 1)
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 1)|||
PID After the fork child === 134513568 & father === 134513632 (i = 2)
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 0)|||
PID After the fork child === 134513568 & father === 134513632 (i = 1)
After the wait child=== 134513568 & father=== 134513632 (i = 1)|||
PID After the fork child === 134513568 & father === 134513632 (i = 2)
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 1)|||
PID After the fork child === 134513568 & father === 134513632 (i = 2)
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
After the wait child=== 134513568 & father=== 134513632 (i = 2)|||
谢谢。
【问题讨论】: