你可以在Shell脚本中如何终止一个刚刚启动的Java进程?

huangapple go评论66阅读模式
英文:

How can I kill a just started Java process in shell script?

问题

我有这个简单的脚本,其中我执行一个.jar文件,并且在sleep命令之后需要它的PID来杀死它:

java -jar test.jar &> output.txt &
pid=$!
sleep 10

问题是:应用程序完全启动后,PID会发生变化,我首先获得的这个PID与应用程序在睡眠10秒后拥有的PID不同(我使用ps检查了它)。

如何追踪PID,以便我可以杀死完全启动的应用程序?

我尝试使用pstree -p $pid,但我得到了一个长列表的Java子进程,我认为可能有比获取每个子进程,使用grep提取PID并杀死它的更好的方法,而且因为我不100%确定这是否有效。

我找到了另一种使用jps的解决方案,但我更愿意使用本机Linux命令以确保兼容性。

我不一定需要PID,使用进程名称也可以,但我不知道如何只使用父进程的PID来检索它。

英文:

I have this simple script where I execute a .jar file and I'd need its PID for killing it after the sleep command:

java -jar test.jar &> output.txt &
pid=$!
sleep 10

The problem is: the PID changes after the application gets fully launched, this pid I get in first place is not the same PID the application has after 10 seconds sleeping (I checked it using ps).

How can I track down the PID so that I can kill the fully launched application?

I've tried using pstree -p $pid but I get a long list of Java children processes and I thought there might be a better way to implement this other than getting every child process, extracting PID using grep and killing it, also because I'm not 100% sure this is working.

I found another solution using jps but I'd prefer use native linux commands for compatibility.

I don't necessarily need PID, using process name could be a way but I don't how to retrieve that either having only parent process' PID.

答案1

得分: 0

如果要使用进程名称,可以运行:

$ kill -9 $(ps aux | grep '[t]est.jar' | awk '{print $2}')

选项详解:

  • kill:发送终止信号(SIGTERM 15: 终止)以优雅地终止任何进程。
  • kill -9:发送终止信号(SIGTERM 9: 终止)以立即终止任何进程。
  • ps:列出所有进程。
  • grep:过滤器,

    防止实际的 grep 进程显示在 ps 结果中。

  • awk:提取每行的第二个字段,即 PID(ps 输出:$1: 用户,$2: PID ...)。
英文:

If you want to use process name, might run :

$ kill -9 $(ps aux | grep '[t]est.jar' | awk '{print $2}')

Options Details:

  • kill: sends a kill signal (SIGTERM 15: Termination) to terminate any process gracefully.
  • kill -9: sends a kill signal (SIGTERM 9:Kill) terminate any process immediately.
  • ps: listing all processes.
  • grep: filtering,

    prevent actual grep process from showing up in ps results.

  • awk: gives the second field of each line, which is PID. (ps output : $1:user, $2:pid ...)

答案2

得分: 0

Two ways.

  1. 使用系统内置函数 system.exit()

或者

  1. 将进程号重定向到文件中,以后再使用它来终止进程。

示例:

java -jar test.jar &> output.txt & echo $! > pid-logs
cat pid-logs | xargs kill -9
英文:

Two ways.

  1. use system. Exit() inbuilt function.

or

  1. redirect the pid number to a file and use later to kill the process.

Ex:-

java -jar test.jar &> output.txt & echo $! > pid-logs
cat pid-logs | xargs kill -9

huangapple
  • 本文由 发表于 2023年1月9日 07:21:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定