Sunday 26 April 2015

Ubuntu daemon

Creating a service on Ubuntu 14.04

Creating a daemon on Ubuntu is quite simple. To run your own daemon scripts on boot-up can be done in the following steps:

Create a daemon in /etc/init.d

The daemon to be run needs to be in the init.d folder. Ubuntu provides a template with the daemon /etc/init.d/skeleton. Therefore copy the skeleton script and name it however you like.

sudo cp /etc/init.d/skeleton /etc/init.d/mydaemon

To be able to run the daemon it it necessary to make it executable

sudo chmod +x /etc/init.d/mydaemon

Adapt the script mydaemon to match your functionality, in the example the executable is in your $HOME/bin directory. The lines to be adapted are highlighted.

#! /bin/sh
### BEGIN INIT INFO
# Provides:          mydaemon
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: My Daemon
# Description:       This file starts my daemon
### END INIT INFO

# Author: Foo Bar 
#
# Please remove the "Author" lines above and replace them
# with your own name if you copy and modify this script.

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/home/user/bin
DESC="my daemon"
NAME=mydaemon
DAEMON= mydaemon
DAEMON_ARGS="--options"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

Afterwards try to start and stop your daemon with

sudo service mydaemon start
sudo service mydaemon stop

Start daemon at boot

To automatically start the daemon at boot time it is necessary to add it to the boot list. This is done with the following command:

update-rd.d mydaemon default 97 03

If you want to remove the daemon again use the following command:

update-rd.d -f mydaemon remove