【发布时间】:2021-08-31 21:22:46
【问题描述】:
我以为我创建了孙子进程并尝试调用 id 以确认它与父进程/第一个子进程 id 之间的不同。有人对此有见解吗?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void) {
int pid;
int pid2;
pid = fork();
wait(NULL);
switch(pid)
{
case -1:
printf("Error: Not able to fork process");
break;
case 0:
printf("This appears to be the child process. The id might be %d \n", getpid());
pid2 = fork();
printf("Grandchild ID? %d\n", getpid());
break;
default:
//printf("Are you my Dad?\n");
printf("Are you my Dad? %d \n",getpid() );
break;
}
//printf("Hello World\n");
return 0;
}
【问题讨论】:
-
请给出准确的预期结果与实际结果。对于第二个
fork调用,您没有区分父进程和子进程。 -
你的代码可能是
fork()ing 就好了。你只会得到两个Grandchild打印输出。一个带有子 pid,一个带有孙 pid。检查this version -
为什么在检查
fork()的返回值之前调用wait()? -
@Shawn 我已经将等待放在检查进程是否是子进程的线上,但我认为我做错了,因为输出不一致。我尝试将等待移到现在的位置,并且得到一致的输出。但是,在我看来,我的第二个 fork 并没有从第一个子进程创建子进程。
-
@kaylum 我认为我的代码会打印以下内容,除了显示孙进程的唯一 ID,但它看起来与子进程相同。我
This appears to be the child process. The id might be 41 Grandchild ID? 41 Are you my Dad? 40