Search code examples
c++boost

Boost - the child process remains as a zombie


I have wrote simple code that runs child process as detached:

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

After the child program finishes, command "top" in ubuntu shows me this entry:

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

Any idea?

#edit This application will run on several operating systems. I have tried some other solutions e.g. threading:

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

Sometimes I get an error "free()". Is this solution correct?


Solution

  • The zombie process remains because a SIGCHLD signal is generated to the parent process when the child process terminates, but the parent process doesn't handle this signal (by reading the child process' status information).

    Assuming the parent process needs to keep running, you can either (in the parent process) :

    • wait for the child process to end (this is a blocking wait) :

      childProcess.wait();
      
    • add a signal handler for SIGCHLD (note this gets a bit trickier if there are multiple child processes), eg. :

      void handle_sigchld(int signum)
      {
          wait(NULL); // or some other wait variant that reads the child process' status information
      }
      signal(SIGCHLD, handle_sigchld);
      
    • ignore the SIGCHLD signal (although this prevents getting status information for any child processes) :

      signal(SIGCHLD, SIG_IGN);
      
    • daemonize the child process