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

我现在的做法是:

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

当前回答

一个只使用awk(和ps)的方法:

ps aux | awk '$11" "$12 == "python csp_build.py" { system("kill " $2) }'

通过使用字符串相等性测试,我防止匹配这个过程本身。

其他回答

如果你想主要在awk中完成,试试吧

  for i in $(jot 5); do 
 (python3 -c 'import sys; [ print(_) for _ in sys.stdin ]' ) & done; 
  
  sleep 1; ps aux | {m,g}awk '

       /[p]ython/ { 
              _=(_)" "$2 
       } END { 
           system("echo \47 kill "(_)" \47")
           system(      "kill -9 " _) }'


[302] 14236
[303] 14237
[304] 14238
[305] 14239
[306] 14240
[303]  + suspended (tty input)  ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[305]  + suspended (tty input)  ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[304]  + suspended (tty input)  ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[302]  + suspended (tty input)  ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[306]  + suspended (tty input)  ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
 
 kill  14239 14237 14236 14240 14238 
 
[305]    killed     ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[303]    killed     ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[306]  + killed     ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[304]  - killed     ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )
[302]  + killed     ( python3 -c 'import sys; [ print(_) for _ in sys.stdin ]'; )

如果你有pkill,

pkill -f csp_build.py

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

这将只返回pid

pgrep -f 'process_name'

因此要在一行中终止任何进程:

kill -9 $(pgrep -f 'process_name')

或者,如果你知道这个过程的确切名称,你也可以试试pidof:

kill -9 $(pidof 'process_name')

但是,如果您不知道进程的确切名称,那么使用pgrep会更好。

如果有多个进程使用相同的名称运行,并且你想杀死第一个进程,那么:

kill -9 $(pgrep -f 'process_name' | head -1)

还要注意的是,如果你担心大小写敏感,那么你可以像在grep中一样添加-i选项。例如:

kill -9 $(pgrep -fi chrome)

更多关于信号和pgrep的信息在man 7信号或man信号和man pgrep

给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

在bash的一行中找到并杀死所有进程。

kill -9 $(ps -ef | grep '<exe_name>' | grep -v 'grep' | awk {'print $2'})

ps -ef | grep '<exe_name>' -给出匹配模式的运行进程详细信息(uname, pid等)的列表。输出列表还包括搜索它的grep命令。现在,对于kill,我们需要忽略这个grep命令过程。 ps -ef | grep' <exec_name>' | grep -v 'grep' -使用-v 'grep'添加另一个grep将删除当前的grep进程。 然后使用awk单独获取进程id。 然后将此命令保存在$(…)中,并将其传递给kill命令,以杀死所有进程。