A simple script for creating a service in java
I've developed recently a runlevel shell script for a java service. I've developed a simple one based on the criteria that it must be adapted to every particular flavor of linux (Ubuntu and SuSE have their particular skeleton files to place a new server, so I imagine that in every case is different.
Here is my script (see below). Once launched the java process as a background server with the & command, it saves the current pid file with the $! special variable, who has the last backgrounded process.
With that I can stop then the process issuing a gentle kill and then a hard kill (just in cas the process is hung).
#!/bin/bash # # java_service.sh - to start / stop a java based service # # JAVA_HOME=PUT-HERE-YOUR-JAVA-HOME JAVA=$JAVA_HOME/bin/java PID_FILE=$SERVER_HOME/pidfile case $1 in start) echo "Starting PUT-YOUR-NAME server" sudo -u USERNAME $JAVA -jar myjar.jar echo $! > "$PID_FILE" echo "done" ;; stop) echo "Stopping PUT-YOUR-NAME server" # first make a gentle kill kill $(cat "$PID_FILE") # then sleep and make a hard kill sleep 4s kill -9 $(cat "$PID_FILE") rm $(cat "$PID_FILE") echo "done" ;; reload) $0 stop $0 start ;; status) if kill -0 $(cat "$PID_FILE") ; then echo "PUT-YOUR-NAME server is running" else echo "PUT-YOUR-NAME server has stopped" fi ;; *) echo "Usage: $0 start | stop | status " ;; esac