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?
Fork to create the background thread and then exec. See a dupe question on this site: http://stackoverflow.com/questions/1509352/can-we-start-a-background-process-using-exec-giving-as-an-argument
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.
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:
int daemon_int(void)
{
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.
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.