【问题标题】:Creating one grandparent, parent, and child process using fork()使用 fork() 创建一个祖父、父和子进程
【发布时间】: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。在许多系统上它们是相同的,但最好不要假设。

标签: c unix pid


【解决方案1】:

fork() 在父节点中不返回 1,而是返回子节点的 pid。

您可能希望将您的 case 1s 更改为 default

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

【讨论】:

  • 知道了。进行适当的更改后,我仍然遇到一些逻辑流错误。这是我的新输出:我是子进程 C,我的 pid 是 8208 我是祖父进程 G,我的 pid 是 8208 我是父进程 P,我的 pid 是 8207 我是祖父进程 G,我的 pid 是 8207我是祖父进程 G,我的 pid 是 8206 我也尝试过休息;内部开关之后的语句,但我得到相同的输出。
  • 我很抱歉。它按应有的方式工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多