Question

I use posix_spawnp to spawn child processes from my main process.

    int iRet = posix_spawnp(&iPID, zPath, NULL, NULL, argv, environ);   

    if (iRet != 0)
    {       
        return false;
    }

Sometimes, after a child process is spawned without errors, it suddenly becomes defunct. How could this occur?

I use a signal handler to reap child processes:

void SigCatcher(int n)
{       
    while(waitpid( -1, NULL, WNOHANG ) > 0);        
}

and I manually call it whenever I kill a child process.

    kill(oProcID, SIGKILL);

    signal (SIGCHLD, SigCatcher);

Could this cause spawned children to go defunct (without me calling kill)?

Was it helpful?

Solution

This:

kill(oProcID, SIGKILL);

signal (SIGCHLD, SigCatcher);

looks like a race condition. You need to install the signal handler before killing the child process, otherwise you risk missing the signal.

OTHER TIPS

Have you called:

signal(SIGCHLD, SigCatcher);

anywhere else?

If you haven't, then you need to do so before any child processes are even spawned to ensure that those children are reaped when they terminate.

As Unwind points out, your current calls to kill and signal are the wrong way around.

Typical use would be:

signal(SIGCHLD, handler);
posix_spawnp(...);
...
// do other stuff
...
kill(pid, SIGKILL);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top