Vlad the Impala
Vlad the Impala

Reputation: 15872

How do I exec() a process in the background in C?

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?

Upvotes: 14

Views: 24418

Answers (4)

Jackson
Jackson

Reputation: 5657

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.

Upvotes: 6

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

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.

Upvotes: 6

user25148
user25148

Reputation:

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.

Upvotes: 0

popester
popester

Reputation: 1934

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?

Upvotes: -1

Related Questions