FreeBSD RC script for Go daemons

The best way of letting a Go program run detached from the terminal on a FreeBSD system is by starting it with daemon(8). We also need a startup script to be able to easily manage our new service. This is done by writing a simple rc(8) script.

Daemonise Go programs

The daemon utility1 launches another program that is run as the given user. It can create a PID-file to manage the program’s execution state and is even able to supervise and restart it on termination.

We will only use if for creating a daemon process under a non privileged user – rc will take care of anything else.

The RC script

The FreeBSD offers an excellent startup script framework rc.subr(8). I will now show the whole script for the imaginary biosphere daemon biod and explain the noteworthy details below.

biod uses a command line argument -c that takes the path to a configuration file.

#!/bin/sh
#
# PROVIDE: biod
# REQUIRE: networking syslog
# KEYWORD: 
 
. /etc/rc.subr
 
name="biod"
rcvar="biod_enable"
command="/usr/local/bin/biod"
 
biod_user="mobile"
biod_config="/usr/local/biosphere/biod.conf"
 
start_cmd="/usr/sbin/daemon -f -u $biod_user $command -c $biod_config"
 
load_rc_config $name
: ${biod_enable:=no}
 
run_rc_command "$1"

start_cmd should be self-explanatory. The -f parameter of daemon pipes all stdout and stderr output to /dev/null, where it belongs as I am doing logging properly via syslog.

biod depends on the syslog daemon as well as a network connection to operate, therefore we declare these two dependencies by using the REQUIRED keyword in the head of the script. rc will then automatically start all daemons in the correct order.

Usage

The script can now be placed into /usr/local/etc/rc.d. It is enabled by specifying biod_enable=“true” inside /etc/rc.conf and can be configured by using the biod_{config,user} variables.

service biod start/stop/status should be working now. The daemon will be automatically started at boot.

If you don’t need auto-starting behaviour you can just omit biod_enable and use service biod onestart/onestop/onerestart for managing the service.

Footnotes


  1. A good Linux alternative is called daemonize

First published on December 27, 2013