我编写了简单的代码,以分离的方式运行子进程:
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()”。 这个解决方案正确吗?
最佳答案
zombie 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);
daemonize子进程
关于c++ - Boost - 子进程仍然是僵尸进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68679894/