Search code examples
c++multithreadingpopenmaster-slave

Get a master program start a slave in a new thread


I am using popen to start a C++ slave program from a master program. However, by doing so control does not return to the master program until the slave has completed its tasks.

How can I start the slave in a separate session (or separate thread), so the master is not forced to wait for it to finish before control is passed back to the master?

I would like the master to be able to start the slave and then finish, with the slave continuing after the master has exited.


Solution

  • To do this you need to fork the main process and then check the pid_t that the fork command returns. From there you can then do an exec or popen as you please.

    When you call fork the calling process gets a pid_t returned (this is the id of the child process you just created). If the pid_t is 0 then this is the newly created process and you can do as you please.

    e.g.

    pid_t childPid  = fork();
    if( childPid == 0 )
    {
        // Do your process create here.
        ...
    
        // Abort this process once it returns control.
        abort(); 
    }