Personal Web Space

Linux – set any program to start as daemon/service

on 3 December, 2012 in Blog | 0 comments

This post explains how to add any program to start a service/daemon on linux (as long as the program supports this). It was created while attempting to start TeamViewer as a daemon while my home server was booting up.

To start any program as a daemon, a link to the daemon script should be placed in /etc/rc*.d/ where * is the number of the boot mode the machine is set to start. In order to find what is your current default mode, please check in file /etc/inittab. Usually these types of daemon scripts are placed in /etc/init.d/ directory.

The below script is a generic script that will start any application/service defined by the user. Simply copy the code below into a file, e.g. /etc/init.d/newdaemon and then create a symbolic link to it from within the directory your machine is booting e.g. # ln -s /etc/init.d/newdaemon /etc/rc3.d/S90daemon

Note that this script was only tested using bash shell. Feel free to use and modify as you like. To test the script is working you can use it like this:

# /etc/rc3.d/S90daemon start

# /etc/rc3.d/S90daemon status

# /etc/rc3.d/S90daemon stop

# /etc/rc3.d/S90daemon status

 


#!/bin/bash
#
#Generic daemon script
#

# source function library
. /etc/rc.d/init.d/functions

RETVAL=0
USER=root
PROG=sshd			# MODIFY THIS
PATHPROG=/usr/sbin/$PROG	# MODIFY THIS

start () {
        echo -n $PROG" starting up "
        $PATHPROG & > /dev/null 2> /dev/null
        sleep 5
	if [ `ps -ef | grep $PROG | grep -v grep | grep -v bash | wc -l` -gt 0 ]
	then
        	success $""
	else
		failure $""
	fi
	echo ""
}

status() {
	if [ `ps -ef | grep $PROG | grep -v grep | grep -v bash | wc -l` -gt 0 ]
	then
		echo -n $PROG" is running..."
		echo ""
	else
		echo -n $PROG" is stopped"
		echo ""
	fi
}

stop () {
        echo -n $PROG" shutting down"
        > /tmp/pid
	chmod 777 /tmp/pid > /dev/null 2> /dev/null
        ps -ef | awk '!/bash/' | awk '/'$PROG'/ {system("echo " $2 " >> /tmp/pid")}'
        cat /tmp/pid | awk '{system("kill -9 " $1 " > /dev/null 2> /dev/null") }'

        sleep 5
        if [ `ps -ef | grep $PROG | grep -v grep | grep -v bash | wc -l` -gt 0 ]
        then
                failure $""
        else
                success $""
        fi
	echo ""
}

case "$1" in
start)
start
;;
status)
status
;;
stop)
stop
;;
*)
echo $"Usage: $0 (start|status|stop)"
RETVAL=1
;;
esac
exit $RETVAL

 

Post a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.