Search code examples
c++linuxforkparent-childspawn

How to Spawn Child Processes that Don't Die with Parent?


I have a C++ program that acts as a watchdog over others. If it detects that a process is no longer running, it restarts it via system. The problem is, if I kill the watchdog process, any processes it has started up also die.

void* ProcessWatchdog::worker(void* arg)
{
    //Check if process is running
    if( !processRunning )
        system("processName /path/to/processConfig.xml &");
}

The new child process gets started correctly, and runs without any problems. But when the parent (now this ProcessWatchdog process) dies, the child dies too. How can I spawn a child process that is fully independent from the parent?

I've tried using pclose and popen, running shell scripts that start processes, and a few other tactics, but to no avail. I'm ignoring SIGHUP signals in the child processes, but they still die.

So ideally, I'd like to tell the system to start a process that is wholly independent from the parent. I want the child's trace to end with the child, and for it/the system to have no idea that ProcessWatchdog started it in the first place.

Is there a way I can do this?

I'm writing this in C++, on Linux.


Solution

  • Try using system with setsid before the process name.

    system("setsid processname /path/to/processConfig.xml &");
    

    This will launch the program in a new session.