Conditionally restarting Linux services


Periodically I need to start a service, but only if it’s not currently running. Other times I need to restart services on a machine, but only if they are currently running. Services may have been started on the system at boot, manually by an admin, or through a systems wide management infrastructure. They may also have been disabled on a server for one reason or another. Most Redhat Linux rc initialization scripts have a “condrestart” target to help facilitate conditionally restarting a server, which can be useful when you need to conditionally start services across dozens of machines.

The conditional restart logic is usually implemented as a test similar to this (I took this from the dnsmasq init script):

condrestart)
            if test "x`pidfileofproc dnsmasq`" != x; then
                stop   
                start
                RETVAL=$?
            fi

This allows the script to restart the service if it’s currently running, but you could alter this behavior to start or restart a service if it’s not running (you can get a bit more fancy and check the result of pidof to see if the process is indeed running):

condrestart)
     [ ! -e /var/lock/subsys/myservice ] && stop && start

This isn’t something you will use every day, but it’s rather handy when you need it. It also helps to know what will happen when you use the “condrestart” logic baked into various system init scripts. If you develop init scripts for services other than the defaults that ship with CentOS, Fedora or RHEL Linux, you may be interested in this!

This article was posted by Matty on 2011-05-17 17:21:00 -0400 EDT