Boost - 子进程仍然是僵尸进程

2024-03-16

我编写了简单的代码,以分离的方式运行子进程:

boost::process::child childProcess
(
    "sleep 10",
    boost::process::std_in.close(),
    boost::process::std_out.close()
);
childProcess.detach();

子程序完成后,ubuntu 中的命令“top”向我显示此条目:

root      8935  0.0  0.0      0     0 pts/0    Z    12:10   0:00 [sleep] <defunct>

任何想法?

#编辑 该应用程序将在多个操作系统上运行。我尝试过其他一些解决方案,例如线程:

 std::thread childProcessThread([](){
    boost::process::child childProcess
    (
        "sleep 10",
        boost::process::std_in.close(),
        boost::process::std_out.close()
    );
    childProcess.wait();
 });
 childProcessThread.detach();
 

有时我会收到错误“free()”。 这个解决方案正确吗?


The 僵尸进程 https://stackoverflow.com/questions/20688982/zombie-process-vs-orphan-process仍然存在,因为SIGCHLD当子进程终止时,会向父进程生成信号,但父进程不会处理该信号(通过读取子进程的状态信息)。

假设父进程需要保持运行,您可以(在父进程中):

  • 等待子进程结束(这是阻塞等待):

    childProcess.wait();
    
  • 添加信号处理程序SIGCHLD(请注意,如果有多个子进程,这会变得有点棘手),例如。 :

    void handle_sigchld(int signum)
    {
        wait(NULL); // or some other wait variant that reads the child process' status information
    }
    signal(SIGCHLD, handle_sigchld);
    
  • 忽略SIGCHLD信号(尽管这会阻止获取任何子进程的状态信息):

    signal(SIGCHLD, SIG_IGN);
    
  • 守护进程 https://stackoverflow.com/questions/17954432/creating-a-daemon-in-linux子进程

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Boost - 子进程仍然是僵尸进程 的相关文章

随机推荐