Tonλ's blog May the λ be with you

Personal Generic Service Wrapper 1/2

by @ardumont on

Problem

I often need to start/stop/restart/status userland command.

Context

I'm running under:

Example

For example, the nm-applet (small graphical applet to deal with network)

You can do this way:

killall nm-applet && killall nm-applet

or this way:

pidof nm-applet | xargs kill -KILL

In any case, for each script/command, you have to repeat the same code.

Generic service wrapper

We can factorize this a simple service wrapper script that orchestrates this behaviour.

Use

Some typical usage would be:

service.sh nm-applet start|stop|status|restart

Script

#!/bin/bash
# Use: $0 {start|stop|restart|status}
# Generic Service Wrapper
# Example:
# $0 <htop|nm-applet|some-personal-script> {start|stop|status|restart}

### functions

# Application that this service wraps
APP=$1
shift

# Send a signal to the nm-applet pid (KILL to kill, 0 to know if it's alive)
app-send() {
    SIG=$1
    mypid=$(pidof $APP)
    [ -z "$mypid" ] && exit 1   # no pid so not running
    kill -$SIG $mypid && exit 0 # if pid exists and the process exists, will return 0
    exit 1 # otherwise problem
}

# Stop application
app-stop() {
    $(app-send KILL)
}

# Start application
app-start() {
    $APP
}

# status
app-status() {
    $(app-send 0)
    ( [ $? = 0 ] && echo "$APP is running!" ) || echo "$APP is not running!"
}

### run

case "$1" in
    start)
        app-start
        app-status
        ;;

    stop)
        app-stop
        app-status
        ;;

    restart)
        app-stop
        app-start
        ;;

    status)
        app-status
        ;;

    *)
        echo "Usage: $0 <APP> {start|stop|restart|status}" >&2
        exit 1
        ;;
esac

Source

Example usage

I use it in my .stumpwmrc configuration file to restart the nm-applet service. This way, when I reload my StumpWM configuration, no new instance is spawned. I have exactly one.

(run-shell-command "~/bin/wifi/nm-applet.sh restart")

where nm-applet.sh simply wraps the call to service.sh:

#!/bin/bash
# Use: $0 {start|stop|restart|status}
# Service Wrapper around nm-applet

~/bin/service/service.sh nm-applet $*

Use in my stumpwm configuration

What about command with arguments?

At the moment, the need has only appeared for command without parameters.

In theory, one would have to:

  • add a small parsing step to retrieve the command name for the stop and status events
  • and keep feeding the full command to the start and restart ones.

Contributions are welcome.

Edit I just published a possible implementation.

Latest posts