如何从同一个父级派生多个进程
How to fork multiple processes from a same parent?
我试图从同一个父级创建多个进程,但最终总是产生比预期更多的进程。我不知道该怎么做,需要一些帮助。
我在网上找到了一段代码并尝试了一下,
int main ()
{
pid_t pid=0;
int i=0;
for (i=0; i<3; i++)
{
pid=fork();
switch(pid)
{
case 0:
{
cout<<"nI am a child and my pid is:"<<getpid();
cout<<endl;
exit(0);
break;
}
default:
{
cout<<"nI am a parent and my pid is: "<<getpid();
cout<<"nMy child pid is: "<<pid;
cout<<endl;
wait(NULL);
break;
}
}
}
return 0;
}
这段代码确实有效,并从同一个父级创建了3个子级。然而,这似乎是因为在创建每个子进程后,它都会立即终止。因此,它不会在下一轮for循环中派生更多的孙进程。但我需要让这些孩子的程序运行一段时间,他们需要与父母沟通。
子进程可能会立即中断循环,在之外继续工作
int main ()
{
cout<<"nI am a parent and my pid is: "<<getpid()<<endl;
pid_t pid;
int i;
for (i=0; i<3; i++)
{
pid=fork();
if(pid == -1)
{
cout<<"Error in fork()"<<endl;
return 1;
}
if(pid == 0)
break;
cout<<"My child "<<i<<" pid is: "<<pid<<endl;
}
if(pid == 0)
{
cout<<"I am a child "<<i<<" and my pid is "<<getpid()<<endl;
wait(NULL); // EDIT: this line is wrong!
}
else
{
cout<<"I am a parent :)"<<endl;
wait(NULL); // EDIT: this line is wrong!
}
return 0;
}
编辑wait(NULL)
行错误。如果该进程没有子进程处于活动状态,则wait()
没有任何作用,因此它在这里的子进程中是无用的。父进程wait()
中的OTOH暂停执行,直到任何子进程退出。我们这里有三个孩子,所以必须wait()
三次。此外,我们无法提前知道孩子完成的顺序,因此我们需要更复杂的代码。类似这样的东西:
struct WORK_DESCRIPTION {
int childpid;
// any other data - what a child has to do
} work[3];
for(i=1; i<3; i++) {
pid=fork();
...
work[i].childpid = pid;
}
if(pid == 0) // in a child
{
do_something( work[i] );
}
else
{
int childpid;
while(childpid = wait(NULL), childpid != 0)
{
// a child terminated - find out which one it was
for(i=0; i<3; i++)
if(work[i].childpid == childpid)
{
// use the i-th child results here
}
}
// wait returned 0 - no more children to wait for
}
相关文章:
- boost::进程间消息队列引发错误
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- IPC使用多个管道和分支进程来运行Python程序
- 异常属于C++中的线程还是进程
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- WMI检测进程创建事件-c++
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 通过 c++ 中的 udp 套接字将派生类对象从一个进程发送到另一个进程
- 如何从同一个父级派生多个进程
- 在派生的线程中启动进程