How to check if a forked process is still running from the c program

混江龙づ霸主 提交于 2020-08-19 11:50:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!