等待子进程
我尝试 fork 子进程并等待它们死亡。我首先 fork N 个子进程,然后循环等待。但它似乎不会等待子进程死亡。尽管子进程没有死亡,但它退出循环。这是我的代码:
void DistributorSubsystem::Start()
{
Application::instance().logger().information("Distributor Subsytem start");
//start all the distributors
pid_t pid = fork();
pid_t p;
for (size_t i=0;i<_distributors.size();++i)
{
switch(pid)
{
case -1:
perror("fork");
exit(-1);
case 0:
p = getpid();
printf("PID=%d\n", p);
_distributors[i]->Start();
Application::instance().logger().information("End of child");
exit(0);
default:
pid = fork();
}
}
int errno;
//wait for child processes to die
while (true)
{
int status;
pid_t done = wait(&status);
if (done == -1)
{
if (errno == ECHILD) break; // no more child processes
}
else
{
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
{
std::stringstream s;
s<<done;
Application::instance().logger().error("pid " + s.str() + " failed");
exit(-1);
}
}
}
Application::instance().logger().information("All started");
}
这是输出:
PID=7311 ThriftDistributor 实例启动: PID=7312 ThriftDistributor 实例启动: 一切开始了 分销商子系统 uninit
I try fork child processes and wait them to die.I first fork N child processes and then wait in a loop. But it seems it doesn't wait the child processes to die.It exits the loop altough the childs do not die. Here's my code:
void DistributorSubsystem::Start()
{
Application::instance().logger().information("Distributor Subsytem start");
//start all the distributors
pid_t pid = fork();
pid_t p;
for (size_t i=0;i<_distributors.size();++i)
{
switch(pid)
{
case -1:
perror("fork");
exit(-1);
case 0:
p = getpid();
printf("PID=%d\n", p);
_distributors[i]->Start();
Application::instance().logger().information("End of child");
exit(0);
default:
pid = fork();
}
}
int errno;
//wait for child processes to die
while (true)
{
int status;
pid_t done = wait(&status);
if (done == -1)
{
if (errno == ECHILD) break; // no more child processes
}
else
{
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
{
std::stringstream s;
s<<done;
Application::instance().logger().error("pid " + s.str() + " failed");
exit(-1);
}
}
}
Application::instance().logger().information("All started");
}
Here's the output:
PID=7311
ThriftDistributor instance start:
PID=7312
ThriftDistributor instance start:
All started
Distributor Subsytem uninit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你通过调用“pid = fork();”又创建了一个子进程在“开关”的默认部分。这个子进程将到达 wait() 函数调用,并且肯定会中断并退出。
真正的父进程将继续运行,直到所有子进程退出。
you created one more child by calling "pid = fork();" in the default section of the "switch". this child will reach the wait() function call and will definitely break and exit.
The real parent process will keep on running till all the children exit.
您不应该在函数中像这样声明
errno
。而是包含头文件
errno.h
(不过不确定这是否会给您带来麻烦)。You shouldn't declare
errno
like this in a function.Include the header file
errno.h
instead (not sure if this is causing your troubles though).