在 Linux 上获取进程 ID 的 Shell 脚本 [英] Shell script to get the process ID on Linux

查看:36
本文介绍了在 Linux 上获取进程 ID 的 Shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 shell 脚本(.sh 文件)来获取给定的进程 ID.我在这里尝试做的是,一旦获得进程 ID,我就想终止该进程.我在 Ubuntu (Linux) 上运行.

I want to write a shell script (.sh file) to get a given process id. What I'm trying to do here is once I get the process ID, I want to kill that process. I'm running on Ubuntu (Linux).

我可以用类似的命令来做到这一点

I was able to do it with a command like

ps -aux|grep ruby
kill -9 <pid>

但我不知道如何通过 shell 脚本来实现.

but I'm not sure how to do it through a shell script.

推荐答案

ps 的结果上使用 grep 在脚本中是个坏主意,因为它也将匹配您刚刚调用的 grep 进程的时间.命令 pgrep 避免了这个问题,所以如果你需要知道进程 ID,这是一个更好的选择.(注意,当然,匹配的进程可能很多.)

Using grep on the results of ps is a bad idea in a script, since some proportion of the time it will also match the grep process you've just invoked. The command pgrep avoids this problem, so if you need to know the process ID, that's a better option. (Note that, of course, there may be many processes matched.)

但是,在您的示例中,您可以使用类似的命令 pkill 来终止所有匹配的进程:

However, in your example, you could just use the similar command pkill to kill all matching processes:

pkill ruby

顺便说一句,您应该意识到使用 -9 几乎在所有情况下都是过度使用 (ho ho) - 在无用的使用 kill-9 套用字母:

Incidentally, you should be aware that using -9 is overkill (ho ho) in almost every case - there's some useful advice about that in the text of the "Useless Use of kill -9 form letter ":

不不不.不要使用kill -9.

它没有给流程一个干净的机会:

It doesn't give the process a chance to cleanly:

  1. 关闭套接字连接
  2. 清理临时文件
  3. 通知它的孩子它正在消失
  4. 重置其终端特性

等等等等.

通常,发送 15,然后等待一两秒钟,如果没有工作,发送 2,如果那不起作用,发送 1.如果那不起作用,删除二进制文件,因为程序表现不佳!

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

不要使用kill -9.不要为了整洁而拿出联合收割机上花盆.

Don't use kill -9. Don't bring out the combine harvester just to tidy up the flower pot.

这篇关于在 Linux 上获取进程 ID 的 Shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆