Can I reap child processes with a detached thread?

I have a scenario like this. Specifically on linux platforms with C++ code. We develop code and APIs for the child process, which is then integrated with several parent applications. Here's a snippet of the code responsible for spawning the child process (exe_path) that is integrated with the parent application.

void childReaper()
{
   wait(NULL);
}   


bool childSpawn()
{
    /* some logic here
    exe_path : path to the child process 
     */
    int child_pid = fork();
    if (child_pid < 0)
    {
        return false;
    }
    else if (child_pid ==0)
    {
        if(execv(exe_path.c_str(),args) == -1)
        {
             return false;   
        }
        exit(0);
    }
    else
    {
        std::thread tReaper(childReaper);
        tReaper.detach();
        return true;
    }

I am running into a situation where lot of these child processes are being left defunct. I cannot configure a signal (userdefined or SIGCHIlD) to reap the child process as several different teams work on a variety of different parent processes (applications) that integrate with the same child process we develop, I simply do not know if the signal is already configured or if it will be configured at some point, as either way would lead to conflicts. Having the parent do a wait call defeats the purpose of spawning a child, if it has to be blocked. My solution was to have the parent spawn a detached thread to wait on the child process. However this doesn't seem to work. The parent process is configured (by the way of child process APIs) to communicate with the child process using the child's port. The child exits a few minutes after the parent stops communicating, also the child exits only after the parent send an 'exit' message as long as the parent is 'alive'. If the parent stops receiving communication from the child, it spawns a new child process after a few minutes. The issue, now, is I do not know what goes with the parent process. There could be a scenario where the parent process could hang and be restarted, and somehow is leading to a lot of these child processes to go defunct.

My questions now:

  1. Can a child process be reaped using a detached thread?
  2. If a single parent process hangs, restarts, spawns a new child, does not wait on it and continues to do this over a period of time, do the child processes get inherited by init when the parent exits? Or what happens to these child processes when they exit?
  3. Even if the parent did wait calls on any child process it spawned, what happens when the parent hangs but recovers?
  4. With little to no control on the parent process (apart from the part where the child process is spawned - childSpawn() here), is there any way I can do a non-blocking wait on the child process without using signals and ensure every child gets reaped when it exits, irrespective of the parent behavior?

Upvotes: 0

Views: 138

Answers (0)

Related Questions