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

我现在的做法是:

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

当前回答

使用-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')

其他回答

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

试着用

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

我开始使用这样的东西:

kill $(pgrep 'python csp_build.py')

如果你有pkill,

pkill -f csp_build.py

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

我的任务是杀死所有与regexp匹配的放在特定目录中的内容(在selenium测试之后,并不是所有内容都停止了)。这招对我很管用:

for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done