使用fork()创建一个祖辈、父辈和子辈进程。

问题描述 投票:0回答:1

我正试图分叉进程,分别创建正好一个祖父母、父辈和子辈,并将每个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
c unix pid
1个回答
0
投票

fork() 并没有在父进程中返回1,而是返回子进程的pid。

你可能想改变你的 case 1default.

还有,在你的外边 switchజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ case 0 落入 case 1. 你可能想要一个 break; 顺其自然 switch在第28和29行之间。

© www.soinside.com 2019 - 2024. All rights reserved.