Running and killing a java application using a shell script (Debian)

I am new to UNIX. I want to run a java application using a script as follows:

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

It supposedly works. It launches the application and writes the pid file. But when I try to stop the process using another script that 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 

My best guess is that I am not writing the correct code in a stop script, possibly without providing the correct command to open the .pid file. Any help would be greatly appreciated.

+6
source share
5 answers

You pass the file name as argument to kill when it expects a number (proces id), so just read the process ID from this file and pass it to kill :

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

Quick and dirty method:

 kill -9 $(cat /var/run/ScriptCheck.pid) 
+2
source

Your syntax is incorrect, kill accepts a process identifier, not a file. You should also not use kill -9 unless you know what you are doing.

 kill $(cat /var/run/ScriptCheck.pid) 

or

 xargs kill </var/run/ScriptCheck.pid 
+2
source

I think you need to read the contents of the ScriptCheck.pid file (which, I assume, contains only one entry with the process PID in the first line).

 #!/bin/sh procID=0; while read line do procID="$line"; done </var/run/ScriptCheck.pid kill -9 procID 
0
source

I never had to create my own pid; Your question was interesting.

Here is the bash code snippet I found:

 #!/bin/bash PROGRAM=/path/to/myprog $PROGRAM & PID=$! echo $PID > /path/to/pid/file.pid 

You will need to have root privileges to put the file.pid file in / var / run associated with many articles, so daemons have root privileges.

In this case, you need to put your pid in a certain place known to your start and terminate the scripts. You can use the fact that a pid file exists, for example, to prevent the second identical process from starting.

$ PROGRAM and puts the script in the background batch.

If you want the program to hang after the script exits, I suggest running it with nohup, which means that the program will not die when your script exits the system.

I just checked. PID is returned with nohup.

0
source

Source: https://habr.com/ru/post/906139/


All Articles