[英]How can I kill a just started Java process in shell script?
I have this simple script where I execute a.jar file and I'd need its PID for killing it after the sleep
command:我有这个简单的脚本,我在其中执行 a.jar 文件,我需要它的 PID 才能在sleep
命令后杀死它:
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
).问题是:应用程序完全启动后 PID 会发生变化,我首先获得的这个 pid 与应用程序在休眠 10 秒后的 PID 不同(我使用ps
检查过)。
How can I track down the PID so that I can kill the fully launched application?如何追踪 PID 以便我可以终止完全启动的应用程序?
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.我试过使用pstree -p $pid
但我得到了一长串 Java 子进程,我认为除了获取每个子进程、使用 grep 提取 PID 并杀死它之外,可能还有更好的方法来实现它,也是因为我我不能 100% 确定这是否有效。
I found another solution using jps
but I'd prefer use native linux commands for compatibility.我找到了另一个使用jps
的解决方案,但我更愿意使用本机 linux 命令以实现兼容性。
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.我不一定需要 PID,使用进程名称可能是一种方式,但我不知道如何检索只有父进程的 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
:发送终止信号(SIGTERM 15: Termination)
以优雅地终止任何进程。kill -9
: sends a kill signal (SIGTERM 9:Kill)
terminate any process immediately. kill -9
: 发送终止信号(SIGTERM 9:Kill)
立即终止任何进程。ps
: listing all processes. ps
:列出所有进程。grep
: filtering, [p]
prevent actual grep process from showing up in ps results. grep
:过滤, [p]
防止实际 grep 进程出现在 ps 结果中。awk
: gives the second field of each line, which is PID. awk
:给出每行的第二个字段,即PID。 (ps output: $1:user, $2:pid...) (ps output: $1:user, $2:pid...)Two ways.两种方式。
or或者
Ex:-前任:-
java -jar test.jar &> output.txt & echo $! > pid-logs
cat pid-logs | xargs kill -9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.