Search code examples
bashubuntuupstart

How can I detect if my upstart script is running?


In pseudo code I'm trying to do something like the following

if myService is running
  restart myService
else
  start myService

How can I translate the above into a bash script or similar?


Solution

  • The standard way is to use a PID file for storing the PID of the service. Then, you can use the PID stored in the PID file to see if the service is already running or not.

    Take a look at the various scripts under the /etc/init.d directory and see how they use the PID file. Also take a look under /var/run in most Linux systems to see where the PID files are stored.

    You can do something like this which is a generic way of handling this for all Bourne shell type shells:

    # Does the PID file exist?
    
    if [ -f "$PID_FILE" ]
    then
        # PID File does exist. Is that process still running?
        if ps -p `cat $PID_FILE` > /dev/null 2&1
        then
    
           # Process is running. Do a restart
           /etc/init.d/myService restart
           cat $! > $PID_FILE
        else
           # Process isn't' running. Do a start
           /etc/init.d/myService start
           cat $! > $PID_FILE
    else
       # No PID file to begin with, do a restart
       /etc/init.d/myService restart
       cat $! > $PID_FILE
    fi
    

    However, on Linux, you can take advantage of pgrep:

    if pgrep myService > /dev/null 2>&1
    then
        restart service
    else
        start service
    fi
    

    Note how you do not use any braces. The if statement operates on the exit status of the pgrep command. I'm outputting both STDOUT and STDERR to /dev/null because I don't want to print them. I just want the exit status of the pgrep command itself.

    READ THE MANPAGE ON PGREP

    There are quite a few options. For example, you might want to use -x to prevent unintended matches, or you might have to use -f to match on the full command line used to start the service.