分叉时重复打印

时间:2018-05-10 19:16:08

标签: c unix fork

我正在使用fork来创建进程树,这是代码:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>    

int main () {


pid_t pid;
printf("Parent of all: %ld\n",(long)getpid());

pid = fork();

if(pid == -1){
   perror("fork failed");
   exit(EXIT_FAILURE);
}
else if (pid == 0){
   pid = fork();
   printf("Child with id: %ld and its Parent id: %ld \n", (long)getpid(),(long)getppid()); 

   if(pid > 0){
      pid = fork();
      printf("Child with id: %ld and its Parent id: %ld \n", (long)getpid(),(long)getppid());    
      _exit(EXIT_SUCCESS);
   }
}
else{
   int status;
   waitpid(pid, &status, 0);
}
   return EXIT_SUCCESS;
}

else if printf行传递给孩子后,所以我得到了相同的东西打印两次,你可以在结果中看到results我可以以某种方式防止这种情况发生吗?

1 个答案:

答案 0 :(得分:4)

当你调用fork时,父进程和子进程将从同一点继续执行,这意味着它们都将执行printf("child with id...)