Fork()的痕迹问题

时间:2012-02-20 12:09:41

标签: unix process fork pid

我有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)|||

感谢。

2 个答案:

答案 0 :(得分:1)

我认为你错过了括号和括号:

   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);
  }

在您的代码中,将在父进程和子进程中调用第二个printf ("After the wait ...)

答案 1 :(得分:1)

您对printf()的论证是getpidgetppid - 当您打算打印调用函数的结果时,您正在传递这些函数的地址。打电话给他们......

printf("PID After the fork child === %d  & father === %d (i = %d) \n\n",(int)getpid(),(int)getppid(),i);