如何检查是否一个进程ID(PID)是否存在 [英] How to check if a process id (PID) exists

查看:352
本文介绍了如何检查是否一个进程ID(PID)是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash脚本,我要做到以下几点(以伪code):

In a bash script, I want to do the following (in pseudo-code):

if [ a process exists with $PID ]; then

    kill $PID 

fi

什么是对的条件语句合适的前pression?

What's the appropriate expression for the conditional statement?

推荐答案

要检查进程的存在,用

kill -0 $PID

但就像@unwind说,如果你打算杀了也无妨,只是

But just as @unwind said, if you're going to kill it anyway, just

kill $PID

或你将有一个竞争条件。

or you will have a race condition.

如果您要根据出口code忽略的文本输出,做一些事情,你可以

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屋!

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