Search code examples
c++spawning

Spawned processes becoming defunct


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)?


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.