Looking to fork a process, in c++, that wont hang its parent process – its parent is a daemon and must remain running. If i wait() on the forked process the forked execl wont defunt – but – it will also hang the app – not waiting fixes the app hang – but the command becomes defunt.
if((pid = fork()) < 0)
perror("Error with Fork()");
else if(pid > 0) {
//wait here will hang the execl in the parent
//dont wait will defunt the execl command
//---- wait(&pid);
return "";
} else {
struct rlimit rl;
int i;
if (rl.rlim_max == RLIM_INFINITY)
rl.rlim_max = 1024;
for (i = 0; (unsigned) i < rl.rlim_max; i++)
close(i);
if(execl("/bin/bash", "/bin/bash", "-c", "whoami", (char*) 0) < 0) perror("execl()");
exit(0);
}
How can I fork the execl without a wait(&pid) where execl’s command wont defunct?
UPDATE
Fixed by adding the following before the fork
signal(SIGCHLD, SIG_IGN);
Still working with my limited skills at a more compatible solution based on the accepted answer. Thanks!
By default,
waitand friends wait until a process has exited, then reap it. You can callwaitpidwith theWNOHANGto return immediately if no child has exited.The defunct/”zombie” process will sit around until you
waiton it. So if you run it in the background, you must arrange to reap it eventually by any of several ways:waitpidwithWNOHANGroutinely:int pid = waitpid(-1, &status, WNOHANG)SIGCHLDto be notified when it exitsAdditionally, under POSIX.1-2001, you can use
sigactionset theSA_NOCLDWAITonSIGCHLD. Or set its action toSIG_IGN. Older systems (including Linux 2.4.x, but not 2.6.x or 3.x) don’t support this.Check your system manpages, or alternative the wait in the Single Unix Specification. The Single Unix Spec also gives some helpful code examples.
SA_NOCLDWAITis documented in sigaction.