Starting and killing java app with shell script (D

2019-03-28 04:07发布

问题:

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

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

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.

回答1:

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


回答2:

A quick and dirty method would be :

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


回答3:

Your syntax is wrong, kill takes a process id, not a file. You also should not be using kill -9 unless you absolutely know what you are doing.

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

or

xargs kill </var/run/ScriptCheck.pid


回答4:

I think you need to read in the contents of the ScriptCheck.pid file (which I'm assuming has only one entry with the PID of the process in the first row).

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


回答5:

I've never had to create my own pid; your question was interesting.

Here is a bash code snippet I found:

#!/bin/bash

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

You would have to have root privileges to put your file.pid into /var/run --referenced by a lot of articles -- which is why daemons have root privileges.

In this case, you need to put your pid some agreed upon place, known to your start and stop scripts. You can use the fact a pid file exists, for example, not to allow a second identical process to run.

The $PROGRAM & puts the script into background "batch" mode.

If you want the program to hang around after your script exits, I suggest launching it with nohup, which means the program won't die, when your script logs out.

I just checked. The PID is returned with a nohup.