【发布时间】:2021-11-28 13:27:54
【问题描述】:
我刚刚进入 C,目前,我正在尝试编写使用 2 forks() 的结果,它应该给我 4 个进程,其中 3 个是子进程。
在下面的代码中,我只有大约 2 个得到 2 个子进程,而不是预期的 3 个。我读到进程数由 2^n 和减 1 来确定子进程?
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork(); // fork #1
pid = fork(); // fork #2
if (pid==0)
{
printf("Child process.\n");
printf(" |-- Child PID: %d\n", getpid());
printf(" |-- Parent PID: %d\n", getppid());
}
else if (pid > 0)
{
printf("Parent process\n");
printf(" |-- Parent PID: %d\n", getpid());
printf(" |-- Child PID: %d\n", pid);
printf("\tWait till the child process is finished...\n");
sleep(100);
printf("\tChild process is now finished.\n");
}
else
{
printf("Fork return error code. No child process.\n");
}
return 0;
}
以下是根据我写的代码输出的结果:
Parent process
|-- Parent PID: 3201
|-- Child PID: 3203
Wait till the child process is finished...
Child process
|-- Child PID: 3203
|-- Parent PID: 3201
Parent process
|-- Parent PID: 3202
|-- Child PID: 3204
Wait till the child process is finished...
Child process
|-- Child PID: 3203
|-- Parent PID: 3201
Child process is now finished.
Child process is now finished.
我是否可能遗漏了一些可能导致缺少子进程的内容?
【问题讨论】:
-
你的一个“父进程”是另一个的子进程,你只是不打印这个事实。
-
@user253751 能否麻烦您与我分享更多关于这方面的见解?我真的看不出我的代码中的哪一行对此做出了贡献
-
当您调用
pid = fork();两次时,您也意识到您正在覆盖pid的存储值。 -
@dissidia 关于@user253751 的声明,当您调用产生子进程的
pid = fork()时。然后你有2个进程。然后这两个进程都调用pid = fork(),这意味着原来的父母现在有两个孩子,第一个孩子现在有一个孩子。 -
这两个进程都将来自第二个分叉的关系存储在
pid中,并忘记他们是第一个分叉的第一个还是第二个孩子