英文:
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.
- 使用系统内置函数
system.exit()
。
或者
- 将进程号重定向到文件中,以后再使用它来终止进程。
示例:
java -jar test.jar &> output.txt & echo $! > pid-logs
cat pid-logs | xargs kill -9
英文:
Two ways.
- use system. Exit() inbuilt function.
or
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论