我经常需要在编程期间终止一个进程。

我现在的做法是:

[~]$ ps aux | grep 'python csp_build.py'
user    5124  1.0  0.3 214588 13852 pts/4    Sl+  11:19   0:00 python csp_build.py
user    5373  0.0  0.0   8096   960 pts/6    S+   11:20   0:00 grep python csp_build.py
[~]$ kill 5124

如何自动提取进程id并在同一行中杀死它?

是这样的:

[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>

当前回答

这里有很多很好的答案-我使用了op接受的答案。只是添加了一个关于pkill和pgrep的小警告。正如你可能从他们的手册页看到的,在你的操作系统上,一些操作系统对进程名有15个字符的限制。-f选项绕过了我的操作系统,但我遇到了麻烦,直到我找到了这个选项!

其他回答

试着用

ps aux | grep 'python csp_build.py' | head -1 | cut -d " " -f 2 | xargs kill

给pkill -f

pkill -f /usr/local/bin/fritzcap.py

.py文件的确切路径为

# ps ax | grep fritzcap.py
 3076 pts/1    Sl     0:00 python -u /usr/local/bin/fritzcap.py -c -d -m

我使用gkill processname,其中gkill是以下脚本:

cnt=`ps aux|grep $1| grep -v "grep" -c`
if [ "$cnt" -gt 0 ]
then
    echo "Found $cnt processes - killing them"
    ps aux|grep $1| grep -v "grep"| awk '{print $2}'| xargs kill
else
    echo "No processes found"
fi

注意:它不会杀死命令行中有“grep”的进程。

你可以用awk和backtics来做

ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`

awk中的$2打印列2,backtics运行打印的语句。

但是一个更干净的解决方案是让python进程将它的进程id存储在/var/run中,然后你可以简单地读取该文件并杀死它。

如果你有pkill,

pkill -f csp_build.py

如果您只想根据进程名(而不是完整的参数列表)进行grep,则取消-f。