Ric*_*d H 169 bash pid process
在bash脚本中,我想执行以下操作(在伪代码中):
if [ a process exists with $PID ]; then
kill $PID
fi
Run Code Online (Sandbox Code Playgroud)
条件语句的恰当表达式是什么?
FDS*_*FDS 240
最好的方法是:
if ps -p $PID > /dev/null
then
echo "$PID is running"
# Do something knowing the pid exists, i.e. the process with $PID is running
fi
Run Code Online (Sandbox Code Playgroud)
问题:
kill -0 $PID
Run Code Online (Sandbox Code Playgroud)
退出代码将是非零,即使pid正在运行,你没有权限杀死它.例如:
kill -0 1
Run Code Online (Sandbox Code Playgroud)
和
kill -0 $non-running-pid
Run Code Online (Sandbox Code Playgroud)
普通用户有一个难以区分的(非零)退出代码,但init进程(PID 1)肯定在运行.
如果测试的主体是"杀戮",那么讨论杀戮和种族条件的答案是完全正确的.我来找一般的" 你如何测试bash中的PID存在 ".
/ proc方法很有意思,但在某种意义上打破了"ps"命令抽象的精神,即你不需要去查看/ proc,因为如果Linus决定调用"exe"文件是什么呢?
Chr*_*röm 170
要检查进程是否存在,请使用
kill -0 $pid
Run Code Online (Sandbox Code Playgroud)
但就像@unwind说的那样,如果你要杀死它,那么就是
kill $pid
Run Code Online (Sandbox Code Playgroud)
或者你会有竞争条件.
如果要忽略文本输出kill
并根据退出代码执行某些操作,则可以
if ! kill $pid > /dev/null 2>&1; then
echo "Could not send SIGTERM to process $pid" >&2
fi
Run Code Online (Sandbox Code Playgroud)
use*_*246 63
if [ -n "$PID" -a -e /proc/$PID ]; then
echo "process exists"
fi
Run Code Online (Sandbox Code Playgroud)
要么
if [ -n "$(ps -p $PID -o pid=)" ]
Run Code Online (Sandbox Code Playgroud)
在后一种形式中,-o pid=
输出格式是仅显示没有标题的进程ID列.非空字符串运算符必须使用引号-n
才能给出有效结果.
ohe*_*ala 33
ps
命令用-p $PID
可以做到这一点:
$ ps -p 3531
PID TTY TIME CMD
3531 ? 00:03:07 emacs
Run Code Online (Sandbox Code Playgroud)
elc*_*uco 11
你有两种方式:
让我们首先在我的笔记本电脑中寻找特定的应用程序:
[root@pinky:~]# ps fax | grep mozilla
3358 ? S 0:00 \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S+ 0:00 \_ grep mozilla
Run Code Online (Sandbox Code Playgroud)
现在所有的例子都将寻找PID 3358.
第一种方法:在第二列中运行"ps aux"和grep for PID.在这个例子中我寻找firefox,然后是它的PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358
Run Code Online (Sandbox Code Playgroud)
所以你的代码将是:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
kill $PID
fi
Run Code Online (Sandbox Code Playgroud)
第二种方式:只需在/proc/$PID
目录中查找内容即可.我在这个例子中使用"exe",但你可以使用其他任何东西.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash
Run Code Online (Sandbox Code Playgroud)
所以你的代码将是:
if [ -f /proc/$PID/exe ]; then
kill $PID
fi
Run Code Online (Sandbox Code Playgroud)
顺便说一句:什么错了kill -9 $PID || true
?
编辑:
在考虑了几个月之后..(大约24 ...)我在这里给出的最初想法是一个很好的黑客,但非常不可移植.虽然它教授了Linux的一些实现细节,但它无法在Mac,Solaris或*BSD上运行.它甚至可能在未来的Linux内核上失败.请 - 使用"ps",如其他回复中所述.
我认为这是一个糟糕的解决方案,可以满足竞争条件.如果这个过程在你的测试和你的杀戮之间死亡怎么办?然后杀死将失败.那么为什么不在所有情况下尝试杀死,并检查其返回值以了解它是如何进行的?
好像你要
wait $PID
Run Code Online (Sandbox Code Playgroud)
$pid
完成后会返回。
否则你可以使用
ps -p $PID
Run Code Online (Sandbox Code Playgroud)
来检查该进程是否仍然存在(这比kill -0 $pid
因为即使您不拥有该pid也会起作用而有效)。
归档时间: |
|
查看次数: |
252888 次 |
最近记录: |