Daemonizing on FreeBSD
FreeBSD provides daemon(8) which can be used to daemonize any process on FreeBSD. We can create an rc.d
script which uses daemon(8)
to daemonize an executable of our choosing. Doing that provides a couple of advantages:
- The operating system will automatically restart the executable if it crashed.
- Option to automatically start service on system boot.
- Full integration into FreeBSD’s system services. You’ll be able to controll your application using
service myapp start
,service myapp stop
and so on.
To achieve this, we have to create an rc.d
script. Fortunately, the base system does all the heavy lifting for us.
The following example allows to deamonize an application named godaemon
:
#!/bin/sh
# PROVIDE: godaemon
# REQUIRE: networking
# KEYWORD:
. /etc/rc.subr
name="godaemon"
rcvar="godaemon_enable"
godaemon_user="godaemon"
godaemon_command="/usr/local/godaemon/godaemon"
pidfile="/var/run/godaemon/${name}.pid"
command="/usr/sbin/daemon"
command_args="-P ${pidfile} -r -f ${godaemon_command}"
load_rc_config $name
: ${godaemon_enable:=no}
run_rc_command "$1"
As the godaemon
application is a local executable and not a system utility, this rc.d
script should be created under /usr/local/etc/rc.d/godaemon
.
The script needs to have the correct permissions. Usually you’d want this to be 555
.
Once everything has been setup correctly you should be able to just type service godaemon start
to start your service. To check wheather the deamonization was successfull, kill the godaemon
process. The operating system should automatically re-start / re-spawn a new instance of godaemon
.