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

我现在的做法是:

[~]$ 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 '^python*'来杀死正则表达式进程。

如果你想知道你要杀死什么或在杀死之前找到什么,只需使用pgrep -l '^python*',其中-l输出进程的名称。如果你不想用 Pkill,用just:

pgrep '^python*' |Xargs Kill

其他回答

一个只使用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 ]'; )
killall -r regexp

-r, --regexp

将进程名模式解释为扩展正则表达式。

这将只返回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

你可以用awk和backtics来做

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

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

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