如何检查进程 ID (PID) 是否存在 [英] How to check if a process id (PID) exists
本文介绍了如何检查进程 ID (PID) 是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 bash 脚本中,我想执行以下操作(在伪代码中):
In a bash script, I want to do the following (in pseudo-code):
if [ a process exists with $PID ]; then
kill $PID
fi
条件语句的适当表达式是什么?
What's the appropriate expression for the conditional statement?
推荐答案
要检查进程是否存在,请使用
To check for the existence of a process, use
kill -0 $pid
但正如@unwind 所说,如果您希望它在任何情况下都终止,那么就
But just as @unwind said, if you want it to terminate in any case, then just
kill $pid
否则你会遇到竞争条件,在第一个 kill -0
之后进程可能会消失.
Otherwise you will have a race condition, where the process might have disappeared after the first kill -0
.
如果你想忽略kill
的文本输出并根据退出代码做一些事情,你可以
If you want to ignore the text output of kill
and do something based on the exit code, you can
if ! kill $pid > /dev/null 2>&1; then
echo "Could not send SIGTERM to process $pid" >&2
fi
这篇关于如何检查进程 ID (PID) 是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文