【发布时间】:2016-03-02 12:58:33
【问题描述】:
我的问题是孩子没有相同的父母并且没有正确显示,这是我的代码:
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid[3];
pid[0] = fork();
if(pid[0] == 0)
{
/* First child */
pid[1] = fork();
if(pid[1] == 0)
{
/* First child continued */
printf("Hello, I'm the first child! My PID is : %d, My PPID is: %d", getpid(), getppid());
sleep(1);
}
else
{
/* Second child */
pid[2] = fork();
if(pid[2] == 0)
{
/* Second child continued */
printf("Hello, I'm the second child! My PID is : %d, My PPID is: %d", getpid(), getppid());
sleep(1);
}
else
{
/* Third child */
printf("Hello, I'm the first child! My PID is : %d, My PPID is: %d", getpid(), getppid());
sleep(1);
}
}
}
else
{
/* Parent */
sleep(1);
wait(0);
printf("Hello, I'm the parent! My PID is : %d, My PPID is: %d", getpid(), getppid());
}
return 0;
}
截至目前,当我运行程序时,我将在 bash 中将其作为输出,其中 bash 的 PID 为 11446:
>Hello, I'm the third child! My PID is: 28738, My PPID is: 28735
>Hello, I'm the first child! My PID is: 28742, My PPID is: 28738
>Hello, I'm the second child! My PID is: 28743, My PPID is: 28738
>Hello, I'm the parent! My PID is: 28753, My PPID is: 11446
如何让第一个孩子出现第一个,第二个孩子出现第二个,第三个孩子最后出现,并让所有孩子都拥有 PPID 28753
【问题讨论】:
-
显然,您的第三个孩子正在创建 child1 和 child2。但是父母的 PID 与您孩子的父母不同。
-
你听说过一种叫做循环的编程结构吗?这是一件很巧妙的事情,它允许您多次执行相同的操作,而无需复制和粘贴代码。
-
如果你 fork 进程,它们会并行运行。如果没有某种明确的同步,或者至少将每个输出的输出延迟更大的数量,你就不能让它们以特定的顺序输出。
-
(如果你想让所有的孩子都拥有同一个父母,那么你必须将他们全部从那个父母分叉。所写的代码有一个孩子叉另一个)。
标签: c linux fork parent-child