瓷瓷的可可 2024-04-03 18:37 采纳率: 100%
浏览 6
已结题

为什么p1==0的分支执行了两次?

为什么p1==0的分支执行了两次?


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

int main(){
 pid_t p1,p2;
 p1=fork();
 p2=fork();
 
 if(p1<0){
  printf("failed");
  exit(0);
 }
 else if(p1==0){
  printf("child progress1  **  PID=%d  PPID=%d  \n",getpid(),getppid());
 }
 else{
  wait(NULL);
  //p2=fork();
  if(p2<0){
   printf("failed");
  }
  else if(p2==0){
   printf("child progress2  **  PID=%d  PPID=%d  \n",getpid(),getppid());
  }
  else{
   wait(NULL);
   printf("parent progress  ** PID=%d  PPID=%d  \n",getpid(),getppid());
  }
  //exit(0);
 }
 return 0;
}
  • 写回答

4条回答 默认 最新

  • 赤露水 2024-04-03 19:46
    关注

    fork被执行了两次,导致进程数翻倍,变成了4个,其中有两个子进程都会走p1==0这个分支

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 4月12日
  • 已采纳回答 4月4日
  • 创建了问题 4月3日