【发布时间】:2020-06-02 16:38:10
【问题描述】:
我正在尝试分叉进程以分别创建一个祖父母、父母和孩子,并将每个 pid 显示到标准输出。我怎样才能做到这一点?这是我当前的代码和输出:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int pid, status, status2;
pid = fork();
switch (pid)
{
case -1: // An error has occured during the fork process.
printf("Fork error.");
break;
case 0:
pid = fork();
switch (pid)
{
case -1:
printf("Fork error.");
break;
case 0:
printf("I am the child process C and my pid is %d\n", getpid());
break;
default:
wait(&status);
printf("I am the parent process P and my pid is %d\n", getpid());
break;
}
default:
wait(&status2);
printf("I am the Grandparent process G and my pid is %d\n", getpid());
break;
}
}
我的输出:
I am the child process C and my pid is 8208
I am the Grandparent process G and my pid is 8208
I am the parent process P and my pid is 8207
I am the Grandparent process G and my pid is 8207
I am the Grandparent process G and my pid is 8206
【问题讨论】:
-
另外一个注意事项:
fork()返回的值应该是pid_t,而不是int。在许多系统上它们是相同的,但最好不要假设。