问题
I have the pid of a forked process. Now, from my c code (running on Linux), I have to check periodically whether this process is still running or terminated. I do not want to use blocking calls like wait()
or waitpid()
. Need (preferably) a non-blocking system call which would just check whether this pid is still running and return the status of the child.
What is best and easiest way to do it?
回答1:
The waitpid()
function can take the option value WNOHANG
to not block. See the manual page, as always.
That said, I'm not sure that pids are guaranteed to not be recycled by the system, which would open this up to race conditions.
回答2:
kill(pid, 0);
This will "succeed" (return 0) if the PID exists. Of course, it could exist because the original process ended and something new took its place...it's up to you to decide if that matters.
You might consider instead registering a handler for SIGCHLD
. That will not depend on the PID which could be recycled.
回答3:
Use the WNOHANG
option in waitpid()
.
来源:https://stackoverflow.com/questions/26381944/how-to-check-if-a-forked-process-is-still-running-from-the-c-program