gpt4 book ai didi

c++ - fork 和等待

转载 作者:行者123 更新时间:2023-11-28 07:09:28 26 4
gpt4 key购买 nike

我正在尝试通过 fork 创建进程的粉丝。我希望 1 个进程成为风扇的基础,所有其他进程从基础派生(所有进程都有相同的父进程,P1 是 P2、P3、P4 等的父进程)。

我已经把这部分写下来了。我真正的问题在于等待父进程(我认为)完成制作 child 。下面是我的代码:

//Create fan of processes
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main()
{
pid_t pid;
cout << "Top Parent: " << getpid() << endl;
for ( int i = 0; i < 9; ++i ) {
pid = fork();
if ( pid ) { //parent process
continue;
} else if ( pid == 0 ) {
cout << "Child: (" << getpid() << ") of Parent: (" << getppid() << ")" << endl;
break;
} else {
cout << "fork error" << endl;
exit( 1 );
}
}
}

我想我需要一些帮助来让输出表现得像它看起来的那样:

Top Parent: 6576
Child: (6577) of Parent: (6576)
Child: (6581) of Parent: (6576)
Child: (6583) of Parent: (6576)
Child: (6579) of Parent: (1)
[remoteuser@server folder]$ Child: (6585) of Parent: (1)
Child: (6584) of Parent: (1)
Child: (6582) of Parent: (1)
Child: (6580) of Parent: (1)
Child: (6578) of Parent: (1)

最佳答案

你应该等到所有的 child 都完成他们的任务,把下面的代码放在父端。

   printf("Parent process started.n");
if ((pid = wait(&status)) == -1)
/* Wait for child process. */ */
perror("wait error");
else { /* Check status. */
if (WIFSIGNALED(status) != 0)
printf("Child process ended because of signal %d.n",
WTERMSIG(status));
else if (WIFEXITED(status) != 0)
printf("Child process ended normally; status = %d.n",
WEXITSTATUS(status));
else
printf("Child process did not end normally.n");
}
printf("Parent process ended.n");

关于c++ - fork 和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234062/

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