Does pthread_join failure cause child process to b

2019-04-13 18:58发布

问题:

I have a C++ pthread Thread invoking shell scripts using Popen.

What is observed in one case is that a pthread_join failure is caught (i.e pthread_join != 0) and the child process remains as zombie ( as per ps output).

This also causes the main program to hang.

Right now, I don't know why the pthread_join would fail, because it never did in other scenarios.

But I would like to know whether collecting the wait status of the child process spawned by Popen is part of thread_join. If so atleast I can be sure that the join failure is the root cause for the zombie and the program hang..

Thanks in advance..

回答1:

After calling popen, there needs to be a corresponding call to pclose, otherwise the child process spawned by the popen call will remain in the zombie state. What might have happened is that the thread encountered an unhandled exception that caused pclose to not be called, resulting in a zombie and a "failed" result of pthread_join.

One solution is to make sure your code properly handles all possible exceptions.

Another solution would be to implement something similar to popen() but does not require pclose() to reap the zombie. This can be accomplished by using a double fork. You call fork(), then call it again before calling exec(). The parent process allows the intermediate child process to exit and be reaped with wait4(). The grandchild process can now exit without leaving a zombie since it will be reaped by the init process. To create a communication channel between the grandchild and parent, use pipe() as popen() does, or socketpair() if you need bidirectional communication. Use dup2() in the grandchild process to allow your choices of stdin, stdout, and stderr to be redirected through the pipe or socket before calling exec().