Question

I've done a fork and exec() on a process, but I'd like to run it in the background. How can I do this? I can just avoid calling waitpid on it, but then the process sits there for ever, waiting to return it's status to the parent. Is there some other way to do this?

Was it helpful?

Solution

Catch SIGCHLD and in the the handler, call wait().

Some flavors of Posix (I think *BSD, but don't quote me on that), if you ignore SIGCHLD, the kernel will automatically clean up zombie process (which is what you are seeing in ps). It's a nice feature but not portable.

OTHER TIPS

I think what you are trying to do is create a daemon process. Read this link on Wikipedia for an explaination.

An example (from Steven's Advanced Programming in the Unix Environment) for making a process a daemon is:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> 

int daemon_int(void)
{
    pid_t pid;
    if ((pid = fork()) < 0)
        return (-1) ;
    else if (pid != 0)
       exit(0) ; /* The parent process exits */
    setsid() ;   /* become session leader */
    chdir("/") ; /* change the working dir */
    umask(0) ;   /* clear out the file mode creation mask */
    return(0) ;
}

Of course this does assume a Unix like OS.

So your program includes the above function and calls it as soon as it is run. It is then disassoicated from it parent process and will just keep running until it terminates or it is killed.

waitpid(-1, &status, WNOHANG) might do what you need: it should return immediately if no child process has exited. Alternatively, you could listen for the SIGCHLD signal.

Fork to create the background thread and then exec. See a dupe question on this site: Can we start a background process using exec() giving & as an argument?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top