Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

process

exec

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?

like image 324
Vlad the Impala Avatar asked Oct 24 '09 18:10

Vlad the Impala


2 Answers

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.

like image 179
R Samuel Klatchko Avatar answered Oct 30 '22 11:10

R Samuel Klatchko


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.

like image 32
Jackson Avatar answered Oct 30 '22 10:10

Jackson