使用 shell 脚本启动和终止 java 应用程序(Debian)

2022-01-24 00:00:00 shell linux debian java

我是 UNIX 新手.我想用这样的脚本启动我的 java 应用程序:

I'm new to UNIX. I want to start my java app with a script like so:

#!/bin/sh
java -jar /usr/ScriptCheck.jar &
echo $! > /var/run/ScriptCheck.pid

这应该是有效的.它确实运行应用程序并且确实写入了 pid 文件.但是当我尝试使用包含以下内容的不同脚本停止该过程时:

This is supposedly working. It does run the app and it does write the pid file. But when I try to stop the process with a different script which contains this:

#!/bin/sh
kill -9 /var/run/ScriptCheck.pid

控制台给了我这个错误:

the console gives me this error:

bash: kill: /var/run/ScriptCheck.pid: arguments must be process or job IDs

我最好的猜测是我没有在停止脚本中编写正确的代码,可能没有给出正确的命令来打开 .pid 文件.任何帮助将不胜感激.

My best guess is that I'm not writing the right code in the stop script, maybe not giving the right command to open the .pid file. Any help will be very appreciated.

推荐答案

kill 需要一个 (proces id) 编号时,您将文件名作为参数传递给它,所以只需阅读来自该文件的进程 ID 并将其传递给 kill:

You're passing a file name as an argument to kill when it expects a (proces id) number, so just read the process id from that file and pass it to kill:

#!/bin/sh 
PID=$(cat /var/run/ScriptCheck.pid) 
kill -9 $PID

相关文章