gpt4 book ai didi

在 C 中创建三个具有相同父项的子项

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:36 26 4
gpt4 key购买 nike

我的问题是 children 没有同一个 parent 并且没有正确出现,这是我的代码:

#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

如何让第一个 child 第一个出现,第二个 child 第二个出现,第三个 child 最后出现,并让所有 child 的 PPID 为 28753

最佳答案

来自 man fork:

RETURN VALUE
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

你的 if-else 条件被交换了。

关于在 C 中创建三个具有相同父项的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35747918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com