分叉和等待
Forking and Waiting
我正在尝试通过分叉创建进程的粉丝。我希望1个过程成为风扇的基础,并且所有其他从基数分叉的进程(所有过程都具有相同的父,P1是父母对P2,P3,P4,...)。
我把这零件放下了。我的真正问题在于等待父母过程(我认为)结束孩子。这是我的代码:
//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)
您应该等到所有孩子完成按照代码的任务完成。
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#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 如何让LLDB在成功时退出,在失败时等待
- 等待整个 omp 块完成,然后再调用第二个函数
- 提升 ASIO - io_service 不要等待连接到线程
- 如何在C++中实现带有packaged_task的异步等待循环?
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- 如何等待窗口隐藏在Qt中?
- 如何在不等待检索的情况下获取C++中的内存位置?
- 等待被迷住了,没有回来
- 等待 WaitForMultipleObjects 窗口中的事件数量可变
- 一个线程等待多个线程事件
- 等待 qthread 终止的正确方法是什么?
- 不可预测的C++睡眠/等待行为
- Bison/flex 在识别规则后等待输入
- 使用记事本C++打开 txt 文件时无需等待
- 接受函数在发送数据包时等待
- 在Visual Studio中运行/调试C ++时,如何在结束时等待输入
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 在等待时破坏condition_variable
- 分叉和等待