这是我用于从父进程创建两个子进程的C代码。 这会成功创造吗?我目前的输出是:
您在父进程中,其ID为29509
您正在使用子进程1,而您的父ID是29509
您在父进程中,其ID为29511
您在子进程2中,而您的父ID是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
答案 0 :(得分:1)
在您的第二个fork
之后,父级和第二个子级执行“父进程”printf
。
答案 1 :(得分:1)
e=getpid();
printf("You are in parent process whose id is %d\n",e);
这些行由父母和孩子执行。