A Minimal FreeBSD rc.d Script

#Freebsd #Init

#!/bin/sh

# PROVIDE: YOUR_SERVICE_NAME
# REQUIRE: LOGIN DAEMON NETWORKING

. /etc/rc.subr

name=YOUR_SERVICE_NAME
rcvar=YOUR_SERVICE_NAME_enable
start_cmd="YOUR_SERVICE_NAME_start"
stop_cmd="YOUR_SERVICE_NAME_stop"

YOUR_SERVICE_NAME_start() 
{
    daemon \
        -r \
        -p /tmp/YOUR_SERVICE_NAME_child_pid \
        -P /tmp/YOUR_SERVICE_NAME_supervisor_pid \
        -o /var/log/YOUR_SERVICE_NAME \
        YOUR_COMMAND
}

YOUR_SERVICE_NAME_stop()
{
    if [ -f /tmp/YOUR_SERVICE_NAME_supervisor_pid ] ; then
        cat /tmp/YOUR_SERVICE_NAME_supervisor_pid | xargs kill -9 
        rm /tmp/YOUR_SERVICE_NAME_supervisor_pid
    fi
    if [ -f /tmp/YOUR_SERVICE_NAME_child_pid ] ; then
        cat /tmp/YOUR_SERVICE_NAME_child_pid | xargs kill -9 
        rm /tmp/YOUR_SERVICE_NAME_child_pid
    fi
}

load_rc_config $name
run_rc_command "$1"

What does this script do? Well…

$ service YOURSERVICENAME start will start a daemon that will then manage YOURCOMMAND. I suggest you read the man page for daemon. In short, -r will reload run YOURCOMMAND again, one second after the command has been terminated. This is helpful if YOURCOMMAND begins a web server that may unexpectedly fail. -p and -P are used to stop and restart the service. Both the daemon process and the YOURCOMMAND process must be stopped at some point in time. kill -9 is used in conjunction with the child and supervisor PID to accomplish this. -o will redirect your commands output to a log file (placed in /var/log/ in this example).

$ service YOUR_SERVICE stop will, well, stop the service.

Please note, the child and supervisor PID are placed into the /tmp/ directory in this example. You probably don’t want it placed there (as other $USER could read).

A file like this should be placed in the /usr/local/etc/rc.d/ directory. The service is first started with $ service YOURSERVICENAME onestart. If it was started successfully, you may want to enable it at boot with $ service YOURSERVICENAME enable. Once the service has been enabled $ service YOURSERVICENAME {start|stop|restart} become available.

I suggest you read more here: Practical rc.d scripting in BSD.

EOF