使用 fork() 创建一个 grandparent、parent 和 child 进程

Creating one grandparent, parent, and child process using fork()

我正在尝试分叉进程以分别创建一个 grandparent、parent 和 child,并将每个 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() 不是 return 1 在父级中,它是 return 子级的 pid。

您可能想将 case 1 更改为 default

此外,在您的外部 switch 中,case 0 落入 case 1。您可能希望在第 28 行和第 29 行之间的内部 switch 之后有一个 break;