Hoa
Hoa

Reputation: 20438

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?

Upvotes: 2

Views: 6681

Answers (2)

David W.
David W.

Reputation: 107030

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.

Upvotes: 6

Alex Oliveira
Alex Oliveira

Reputation: 922

If you see myService when you run a ps aux, then you could simply do this in bash (edited to use pgrep, as jordanm suggested):

if [ $(pgrep myService) ]; then
    restart myService;
else
    start myService;
fi

Upvotes: 0

Related Questions