问题

我经常需要在编程过程中杀掉一个进程.

我现在的方式是:

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


解决方法

bash 中,您应该能够:

kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')

其工作细节如下:

  • The ps gives you the list of all the processes.
  • The grep filters that based on your search string, [p] is a trick to stop you picking up the actual grep process itself.
  • The awk just gives you the second field of each line, which is the PID.
  • The $(x) construct means to execute x then take its output and put it on the command line. The output of that ps pipeline inside that construct above is the list of process IDs so you end up with a command like kill 1234 1122 7654.

以下是一个演示文稿:

pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+  Terminated              sleep 3600
[1]   Terminated              sleep 3600
[2]   Terminated              sleep 3600
[3]-  Terminated              sleep 3600
[4]+  Terminated              sleep 3600
pax> _

您可以看到它终止了所有的睡眠者.


稍微解释 grep'[p] ython csp_build.py'位:

当您执行 sleep 3600&amp; 后跟 ps -ef | grep sleep ,你倾向于使用 sleep 来获取两个进程, sleep 3600 grep sleep < / code>(因为他们都有 sleep 在他们,这不是火箭科学).

但是, ps -ef | grep'[s] leep'不会在其中创建 sleep 的进程,而是创建 grep'[s] leep'位: grep 找不到它,因为它正在寻找正则表达式"任何字符从字符类 [s] (这是 s ),后跟 leep .

换句话说,它寻找 sleep ,但grep进程是 grep'[s] leep',它没有 sleep 在其中.

当我看到这个(由SO的某人在场)时,我马上开始使用它,因为

  • it's one less process than adding | grep -v grep; and
  • it's elegant and sneaky, a rare combination :-)



相关问题推荐