Thursday, February 8, 2024

FreeBSD: Creating your own service/daemon

If you have a certain program that needs to be launched as a service in the FreeBSD, follow these steps:

1. Create and edit a configuration file for your service "ee /etc/rc.d/myapp".

Below is an example of a simple launch of an application called "myapp" using the "start" command and killing the process using the "stop" command.

#!/bin/sh
#
#
# REQUIRE: LOGIN FILESYSTEMS
. /etc/rc.subr
name=myapp
rcvar=myapp_enable
load_rc_config $name
pidfile=/var/run/myapp.pid
start_cmd='/sbin/myapp ; echo $(pgrep myapp) > /var/run/myapp.pid ; echo myapp is now running on PID $(cat $pidfile)'
stop_cmd='killall -v $name > /dev/null ; echo myapp is not running. ; rm $pidfile'
status_cmd='if [ -e $pidfile ]; then echo myapp is running on PID $(cat $pidfile). ; return 1; fi; echo myapp is not running. ; return 0'
run_rc_command "$1"


2. Add execution rights to this configuration file: "chmod +x /etc/rc.d/myapp".

3. Next, in the file "/etc/rc.conf" you need to add permission to start the service with the command "echo myapp_enable="YES" >> /etc/rc.conf". Also in this case, your application will always start when the OS boots.

No comments:

Post a Comment