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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With