51

I am trying to make a linux executable as a service

I execute my program like this below

java -jar mytestprogram.jar

creates a process that runs continuously and serves REST requests. But I want to run it as a service where I can do

service mytestprogram start
service mytestprogram stop
service mytestprogram status
chkconfig mytestprogram on

etc. What is the most simple way of doing it?

mido
  • 24,198
  • 15
  • 92
  • 117
yalkris
  • 2,596
  • 5
  • 31
  • 51
  • 1
    There is no single way to do this: it all depends on the particular Linux distribution and the service management daemon that comes with it. The major ones are System V, upstart, and systemd by the timeline. Choose the one that matches your distribution best. Here's the tutorial: https://www.digitalocean.com/community/tutorials/how-to-configure-a-linux-service-to-start-automatically-after-a-crash-or-reboot-part-1-practical-examples – smwikipedia Aug 17 '18 at 02:39

3 Answers3

56

That depends on your system manager

the most common way to do that on debian/ubuntu is to build an initscript and place it in /etc/init.d or /etc/rc/init.d and place a script named mytestprogram in that.

this is an example initscript:

#!/bin/sh
### BEGIN INIT INFO
# Provides:          testone
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     false
# Short-Description: Example init script
# Description:       Start/stop an example script
### END INIT INFO

DESC="test script"
NAME=testone
#DAEMON=

do_start()
{
   echo "starting!";
}

do_stop()
{
   echo "stopping!"
}


case "$1" in
   start)
     do_start
     ;;
   stop)
     do_stop
     ;;
esac

exit 0

I suggest you to look some scripts in that directory, It's simple if you know bash a little ;)

SpectralWave
  • 971
  • 9
  • 18
  • 1
    That worked. Thanks. Let me also try if it works on a centOS system – yalkris Mar 13 '14 at 16:26
  • 7
    Also remember to set the file executable `chmod +x filename` – Christian Sep 14 '14 at 10:15
  • Are the comments in the first few lines necessary ? (ex. # Required-Stop: $java ) is there some parsing of comments ? Or, is this a good practice that everyone is following and code works fine without the comments ? – Vasif Apr 26 '17 at 23:02
  • what about `chkconfig mytestprogram on`? – Jared Chu Jul 19 '17 at 09:05
  • 1
    Do we need to restart the machine to take this script into effect? I created a script like one mentioned, but couldn't use it immediately. – Aakash Apr 12 '18 at 05:45
21

Here is a sample shell script (make sure you replace the MAT name with the name of the your application):

I create one GitHubGist with the latest version of my script and a brief explanation to help those who need it. GitHub Gist link

#!/bin/bash

### BEGIN INIT INFO
# Provides:                 MATH
# Required-Start:           $java
# Required-Stop:            $java
# Short-Description:        Start and stop MATH service.
# Description:              -
# Date-Creation:            -
# Date-Last-Modification:   -
# Author:                   -
### END INIT INFO

# Variables
PGREP=/usr/bin/pgrep
JAVA=/usr/bin/java
ZERO=0

# Start the MATH
start() {
    echo "Starting MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        echo "The service is already running"
    else
        #Run the jar file MATH service
        $JAVA -jar /opt/MATH/MATH.jar > /dev/null 2>&1 &
        #sleep time before the service verification
        sleep 10
        #Verify if the service is running
        $PGREP -f MATH  > /dev/null
        VERIFIER=$?
        if [ $ZERO = $VERIFIER ]
        then
            echo "Service was successfully started"
        else
            echo "Failed to start service"
        fi
    fi
    echo
}

# Stop the MATH
stop() {
    echo "Stopping MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        #Kill the pid of java with the service name
        kill -9 $($PGREP -f MATH)
        #Sleep time before the service verification
        sleep 10
        #Verify if the service is running
        $PGREP -f MATH  > /dev/null
        VERIFIER=$?
        if [ $ZERO = $VERIFIER ]
        then
            echo "Failed to stop service"
        else
            echo "Service was successfully stopped"
        fi
    else
        echo "The service is already stopped"
    fi
    echo
}

# Verify the status of MATH
status() {
    echo "Checking status of MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        echo "Service is running"
    else
        echo "Service is stopped"
    fi
    echo
}

# Main logic
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart|reload)
        stop
        start
        ;;
  *)
    echo $"Usage: $0 {start|stop|status|restart|reload}"
    exit 1
esac
exit 0
  • 1
    Are the comments in the first few lines necessary ? (ex. # Required-Stop: $java ) is there some parsing of comments ? Or, is this a good practice that everyone is following and code works fine without the comments ? – Vasif Apr 26 '17 at 23:02
  • 2
    These comments are good practices and also serve for other people to analyze what is necessary to use your application. Would they be the same as the minimum requirements of a game ... are they vital? No. But it helps those who will use it to know what it needs to be able to use. – Matheus Sant Anna de Oliveira Apr 27 '17 at 10:50
0

In Ubuntu you can create the file as explained above with few lines, play around and see if it works for you.

description "My prog"
 
 
start on (net-device-up
          and local-filesystems
          and runlevel [2345])

stop on runlevel [!2345]
 
respawn
respawn limit 10 5
 
setuid root
setgid shnmon
 
script
    /usr/local/bin/my_script -config.path /etc/myprog/yourconfig.xyz -children false >> /var/log/myprog.log 2>&1
end script

The "-config.path /etc/myprog/yourconfig.xyz" is optional incase you have a config file.

You can just edit the script part and test it and keep others default and edit the rest along the way

Impermanence
  • 146
  • 1
  • 4