检查过程中存在给予其PID [英] Check if process exists given its pid

查看:131
本文介绍了检查过程中存在给予其PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Linux进程的PID,我要检查,从C程序,如果进程仍在运行。

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

推荐答案

发出 杀(2 ) 系统调用 0 作为信号。如果呼叫成功,则意味着与该PID的过程中存在

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

如果调用失败和错误号设置为 ESRCH ,这样的PID的过程不存在。

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

引述POSIX标准:

如果签名是0(空信号),则进行错误检查,但没有
  信号实际上被发送。该空信号可以被用来检查
  PID的有效性。

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.

请注意,你是不是在竞争条件安全:有可能是目标进程已退出,并具有相同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.

只有当给定的pid是一个子进程的(从当前ED),你可以使用的 waitpid函数(2) WNOHANG 选项,或者试图抓住 SIGCHLD 信号。这些都是从竞争条件安全,但只有子进程相关的。

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.

这篇关于检查过程中存在给予其PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆