Check if process exists given its pid

泪湿孤枕 提交于 2020-01-09 06:21:19

问题


Given the pid of a Linux process, I want to check, from a C program, if the process is still running.


回答1:


Issue a kill(2) system call with 0 as the signal. If the call succeeds, it means that a process with this pid exists.

If the call fails and errno is set to ESRCH, a process with such a pid does not exist.

Quoting the POSIX standard:

If sig is 0 (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid.

Note that you are not safe from race conditions: it is possible that the target process has exited and another process with the same pid has been started in the meantime. Or the process may exit very quickly after you check it, and you could do a decision based on outdated information.

Only if the given pid is of a child process (fork'ed from the current one), you can use waitpid(2) with the WNOHANG option, or try to catch SIGCHLD signals. These are safe from race conditions, but are only relevant to child processes.




回答2:


Use procfs.

#include <sys/stat.h>
[...]
struct stat sts;
if (stat("/proc/<pid>", &sts) == -1 && errno == ENOENT) {
  // process doesn't exist
}

Easily portable to

  • Solaris
  • IRIX
  • Tru64 UNIX
  • BSD
  • Linux
  • IBM AIX
  • QNX
  • Plan 9 from Bell Labs



回答3:


kill(pid, 0) is the typical approach, as @blagovest-buyukliev said. But if the process you are checking might be owned by a different user, and you don't want to take the extra steps to check whether errno == ESRCH, it turns out that

(getpgid(pid) >= 0)

is an effective one-step method for determining if any process has the given PID (since you are allowed to inspect the process group ID even for processes that don't belong to you).




回答4:


You can issue a kill(2) system call with 0 as the signal.

There's nothing unsafe about kill -0. The program must be aware that the result can become obsolete at any time (including that the pid can get reused before kill is called), that's all. And using procfs instead does use the pid too, and doing so in a more cumbersome and nonstandard way.




回答5:


As an addendum to the /proc filesystem method, you can check the /proc/<pid>/cmdline (assuming it was started from the command line) to see if it is the process you want.




回答6:


ps -p $PID > /dev/null 2>&1;   echo $?

This command return 0 if process with $PID is still running. Otherwise it returns 1.

One can use this command in OSX terminal too.



来源:https://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid

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