gpt4 book ai didi

c - 为什么主进程会在没有循环的情况下创建许多子进程?

转载 作者:行者123 更新时间:2023-12-02 03:21:25 24 4
gpt4 key购买 nike

我正在使用 Eclipse Luna IDE 在 Debian 发行版下使用 C 语言进行编程。

我程序的主进程应该只执行一次,因此只创建 3 个子进程,然后在所有子进程结束后结束。

我看不出我的代码有什么问题,但我的程序创建了超过 3 个不同父亲的 child 。

谁能告诉我如何获得预期的输出?

似乎 main 函数执行了不止一次,但它没有执行它的循环。

这是我的代码:

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

int main(){

pid_t IMU1_PID, IMU2_PID, IMU3_PID;

IMU1_PID=fork();
IMU2_PID=fork();
IMU3_PID=fork();

if (IMU1_PID<0 || IMU2_PID<0 || IMU3_PID<0) { perror("fork"); exit(errno);}

if(IMU1_PID==0){
printf("child1's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}
if(IMU2_PID==0){
printf("child2's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}
if(IMU3_PID==0){
printf("child3's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}

printf("PARENT %d waiting until all CHILDS end\n",getpid());
while(wait(NULL)!=-1);
printf("PARENT %d after all CHILDS ended\n",getpid());

return 0;
}

这里是输出:

PARENT 4282 waiting until all CHILDS end
child3's PID: 4285 - father's PID: 4282
child2's PID: 4284 - father's PID: 4282
child2's PID: 4286 - father's PID: 4284
child1's PID: 4288 - father's PID: 4283
child1's PID: 4283 - father's PID: 4282
child1's PID: 4287 - father's PID: 4283
child1's PID: 4289 - father's PID: 4287
PARENT 4282 after all CHILDS ended

这是我所期望的:

PARENT 4282 waiting until all CHILDS end
child3's PID: 4285 - father's PID: 4282
child2's PID: 4284 - father's PID: 4282
child1's PID: 4288 - father's PID: 4282
PARENT 4282 after all CHILDS ended

最佳答案

用 Erik Eidt 的话来说“当你 fork 时,根据定义,fork() 的函数的其余部分(在这种情况下,main) 在原始进程和新创建的进程中执行。"

正如 Charles 所写,我之前的代码在调用 fork() 的第 2 次或第 3 次调用之前不会检查 pid!初始进程调用第一个 fork(),然后父进程和第一个子进程都调用第二个 fork(),然后原始进程和两个子进程中的每一个都会调用第三个 fork()

下面是正确的代码:

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

int main(){

pid_t IMU1_PID, IMU2_PID, IMU3_PID;

IMU1_PID=fork();
if (IMU1_PID<0) { perror("fork"); exit(errno);}
if(IMU1_PID==0){
printf("child1's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}

IMU2_PID=fork();
if (IMU2_PID<0) { perror("fork"); exit(errno);}
if(IMU2_PID==0){
printf("child2's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}

IMU3_PID=fork();
if (IMU3_PID<0) { perror("fork"); exit(errno);}
if(IMU3_PID==0){
printf("child3's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}

printf("PARENT %d waiting until all CHILDS end\n",getpid());
while(wait(NULL)!=-1);
printf("PARENT %d after all CHILDS ended\n",getpid());

return 0;
}

关于c - 为什么主进程会在没有循环的情况下创建许多子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com