仅杀死特定 Java jar 的进程(实例)

Kill only processes (instances) of specific Java jar

我需要创建自动脚本,它会终止特定 Java 个 JAR 的 运行 个进程。

我是这样手动操作的:

jps -v

6753 Jps
4573 myJarToKill.jar
4574 notMyJarToKill.jar
4576 myJarToKill.jar

我根据 JAR 名称选择特定进程,例如 myJarToKill.jar 和 运行 杀死它们。

kill 4573 4576  

是否可以通过grep 或类似这样的方式获取此进程的数量?将其传递给 kill 命令?

kill `jps -v |grep myJarToKill|cut -f1 -d " "`

cut -f1 -d " " 是提取第一个 "column" 的部分。 ` 中的命令被执行,结果作为参数提供给 kill。

要使用的命令是 grep、awk 和 xargs unix 命令的组合:

jps -v | grep "<your file name>" | grep -v "<if you need to exclude other output>" |awk '{print $<field number>}'|xargs kill -<kill signal>

执行前请阅读以下说明:

首先运行这个: jps -v | grep "myJarToKill.jar" | awk '{print $1}'

Note: </code> means that the ps output is splitted in space separated field. So when you run the command for the first time please check that <code>awk '{print }' output is the expected result otherwise you should change the field number </code> with the ones that you need.</p> </blockquote> <p>如果 "notMyJarToKill.jar" 仍然存在,请添加:</p> <pre><code>jps -v | grep "myJarToKill.jar" | grep -v "notMyJarToKill.jar"| awk '{print }'

然后如果输出结果包含你要杀死的pid你可以运行这个

jps -v  | grep "myJarToKill.jar" | awk '{print }'|xargs kill -9 

Note: you could also use kill -TERM it's depend by your needs.

问候 克劳迪奥