如何在不意外包含不相关进程的情况下匹配并终止特定进程?

How do I match and kill a specific process without accidentally including unrelated processes?

我有两个Tomcat进程,一个叫event-ws,另一个叫app-event-ws。我有时需要从 shell 脚本中杀死 event-ws

ps -ef | grep -w event-ws | grep -v grep

以上将找到并杀死他们两个;我怎样才能准确找到其中之一?

pgrep / pkill 是在这种情况下使用的最佳工具,代替 of ps:

 pgrep -x event-ws   # match by executable filename 'event-ws'; print PID
 pkill -x event-ws   # match and kill

每个命令匹配可执行文件名event-ws完全的进程(-x)(无论启动可执行文件时是否使用了目录路径前缀)。

但是请注意,您的 pgrep / pkill 实施可能会将名称限制为 15 个字符 - 无论是在匹配时还是在其输出中。

pgrep 只是 打印 匹配的 PID(进程 ID),而 pkill kills匹配过程。


相比之下,如果您需要匹配完整命令行的 部分 ,请使用带有 正则表达式的 -f 选项:

pgrep -f '/event-ws/' # match by part of the full command line; print PID and name
pkill -f '/event-ws/' # match and kill

如果将 -l 添加到 pgrep 命令,将打印匹配进程的完整命令行,而不仅仅是进程名称。