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

我现在的做法是:

[~]$ 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>

当前回答

给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

其他回答

我开始使用这样的东西:

kill $(pgrep 'python csp_build.py')
ps -o uid,pid,cmd|awk '{if($1=="username" && $3=="your command") print $2}'|xargs kill -15

我使用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”的进程。

使用-C ps命令的标志

- c cmdlist 按命令名选择。它选择的进程 可执行文件名称在cmdlist中给出。

第一个例子,简单的命令

所以如果你用标准shebang运行你的脚本,并调用他们的名字:

/path/to/csp_build.py

你可能会找到他们

ps -C csp_build.py

So

kill $(ps -C csp_build.py ho pid)

也许足够了。

第二种情况,搜索CMD

更强烈一点,但仍然比这个SO问题的大多数其他答案快得多…

如果你不知道这是谁,或者你只是匆匆走过

python csp_build.py
python3 csp_build.py
python /path/to/csp_build.py

你可以通过以下方式找到它们:

ps -C python,python3,csp_build.py who pid,cmd | grep csp_build.py

然后使用sed:

kill $(ps -C python,python3,csp_build.py who pid,cmd |
    sed -ne '/csp_build.py/s/^ *\([0-9]\+\) .*$/\1/p')

给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