gpt4 book ai didi

c - 此代码是否会导致从父进程成功创建两个子进程?

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:50 24 4
gpt4 key购买 nike

这是我的 C 代码,用于从父进程创建两个子进程。这样能创建成功吗?我当前的输出是:

You are in parent process whose id is 29509
you are in child process 1 and your parent id is 29509
You are in parent process whose id is 29511
you are in child process 2 and your parent id is 29509

为什么在我输出的第三行中父 ID 不同??

    #include<stdio.h>
#include<unistd.h>
int main(){
pid_t child1,child2;
int c,d,e;
child1=fork();
if(child1==0){
c=getppid();
printf("you are in child process 1 and your parent id is %d\n",c);

}
else{
child2=fork();
e=getpid();
printf("You are in parent process whose id is %d\n",e);
}
if(child2==0){
d=getppid();
printf("you are in child process 2 and your parent id is %d\n",d);
}
}

输出是

You are in parent process whose id is 29509
you are in child process 1 and your parent id is 29509
You are in parent process whose id is 29511
you are in child process 2 and your parent id is 29509

最佳答案

在您的第二个fork 之后,父进程和第二个子进程都执行“父进程”printf

关于c - 此代码是否会导致从父进程成功创建两个子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382527/

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