Running daemon process in linux

Daemonizing a Process in Linux

Most of the times when we need to run some Java, Node.js or python program in background, so it could stay running even after you leave console all we do is put “&” in the end of the command.

$java -jar SimpleService.jar &

The problem here is that when you leave the bash shell your process will become “Orphan” and it’s up to the OS if INIT should adopt the process or kill the process.

To fix this we can force the process to be detached from your shell and become child process of INIT by putting nohup in front of command.

$nohup java -jar SimpleService.jar &

It’s all good for testing purposes, but services are supposed to run as “daemons” under some service supervisor. You can find many service supervisors with which you manage your services on Linux and we will cover few of the defaults that come with Linux.

Why do you need it ?

a. auto start/stop the service on startup/shutdown
b. controlling which service should start first
c. controlling which service should stop first is equally important
d. INIT controlled processes directly which provides more options like respawn, post-start, etc..

Ubuntu services using Upstart

Modify the script according to your setup:

$sudo vi /etc/init/java-app.conf

[js]author «nitin»
description «start and stop java-app for Ubuntu (upstart)»
version «1.0»

start on started networking
stop on runlevel [!2345]

# Automatically Respawn a process if fails, try max 5 times in 60 sec then give up
respawn
respawn limit 5 60

# Open files Limit
limit nofile 32768 32768

env APPUSER=»admin»
env APPBIN=»/usr/bin/java»
env APPARGS=»-jar /opt/app/SimpleService.jar»

script
exec su – $APPUSER -c «$APPBIN $APPARGS»
end script

post-stop script
sleep 2
end script[/js]

Check the configuration:
$init-checkconf /etc/init/java-app.conf

Reload New configuration:
$sudo initctl reload-configuration

Check is service is known to Upstart:
$sudo initctl list |grep java

Start the service with:
$sudo start java-app

Note: For any errors look into /var/log/syslog and /var/log/upstart/*

Debian and Ubuntu services using SysVinit

Modify the script according to your setup.

Читайте также:  Условия использования astra linux

### BEGIN INIT INFO
# Provides: daemon
# Required-Start: $local_fs $network $syslog
# Required-Stop: $local_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Java-app
# Description: Java-app start-stop-daemon – Debian
### END INIT INFO

NAME=»java-app»
PATH=»/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin»
APPDIR=»/opt/app»
APPBIN=»/usr/bin/java»
APPARGS=»-jar /opt/app/SimpleService.jar»
USER=»admin»
GROUP=»admin»

# Include functions
set -e
. /lib/lsb/init-functions

start() printf «Starting ‘$NAME’… »
start-stop-daemon –start –chuid «$USER:$GROUP» –background –make-pidfile –pidfile /var/run/$NAME.pid –chdir «$APPDIR» –exec «$APPBIN» — $APPARGS || true
printf «done\n»
>

#We need this function to ensure the whole process tree will be killed
killtree() local _pid=$1
local _sig=$
for _child in $(ps -o pid –no-headers –ppid $); do
killtree $ $
done
kill -$ $
>

stop() printf «Stopping ‘$NAME’… »
[ -z `cat /var/run/$NAME.pid 2>/dev/null` ] || \
while test -d /proc/$(cat /var/run/$NAME.pid); do
killtree $(cat /var/run/$NAME.pid) 15
sleep 0.5
done
[ -z `cat /var/run/$NAME.pid 2>/dev/null` ] || rm /var/run/$NAME.pid
printf «done\n»
>

status() status_of_proc -p /var/run/$NAME.pid «» $NAME && exit 0 || exit $?
>

Make sure the script is executable:
$chmod +x /etc/init.d/java-app

Enable the service to auto start in runlevel 2345:
$update-rc.d java-app defaults

Start the service with:
$service java-app start

CentOS/Redhat services using SysVinit

Modify the parameter according to your setup:
$sudo vi /etc/init.d/example

[js]#!/bin/sh
#
# example start stop daemon for CentOS (sysvinit)
#
# chkconfig: – 64 36
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 2 3 4 6
# Required-Start:
# description: java-app start stop daemon for CentOS
# processname: java-app
# pidfile: none
# lockfile: /var/lock/subsys/java-app

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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ «$NETWORKING» = «no» ] && exit 0

USER=»admin»
APPNAME=»java-app»
APPBIN=»/usr/bin/java»
APPARGS=»-jar /opt/app/SimpleService.jar»
LOGFILE=»/var/log/$APPNAME/error.log»
LOCKFILE=»/var/lock/subsys/$APPNAME»

start() [ -x $prog ] || exit 5
[ -d $LOGPATH ] || mkdir $LOGPATH
[ -f $LOGFILE ] || touch $LOGFILE

echo -n $»Starting $APPNAME: »
daemon –user=$USER «$APPBIN $APPARGS >>$LOGFILE &»
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $LOCKFILE
return $RETVAL
>

stop() echo -n $»Stopping $APPNAME: »
killproc $APPBIN
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f $LOCKFILE
return $RETVAL
>

Make sure the script is marked as executable:
$sudo chmod +x /etc/init.d/java-app

Enable the service to auto start at runlevels 2345:
$sudo chkconfig java-app on

Start the service with:
$sudo service java-app start

This is how simple it is to daemonize a process. In my next blog, I will talk about more interesting features available in Linux OS.

Источник

Run bash script as daemon

To run it as a full daemon from a shell, you’ll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null & 

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

Читайте также:  Linux задание пароля пользователя

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

You'll have to find it's pid and send it a signal. Here's an UNSAFE example for linux systems: kill $(ps -fade | grep myscript.sh | grep -v grep | awk '') . This will kill all processes which contain "myscript.sh" in their name or parameters so it's not very safe to use, but you can tweak it to suite your needs.

@DanielPatrick in bash (and most other shells) this is stdin/stderr/stdout redirection. The > /dev/null (same as 1>/dev/null ) redirects stdout (which is file descriptor 1) to /dev/null. The 2>&1 means redirect all stderr (file descriptor 2) to file descriptor 1, which is already redirected to /dev/null. The

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user.

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

Add the following and save:

#For a BASH script /bin/sh TheNameOfYourScript.sh > /dev/null & 

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf 
description "My Daemon Job" author "Your Name" start on runlevel [2345] pre-start script echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log end script exec /bin/sh TheNameOfYourScript.sh > /dev/null & 
init-checkconf /etc/init/TheNameOfYourDaemon.conf 

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat /var/log/TheNameOfYourDaemonJobLog.log 

• Now you may start/stop/restart/get the status of your Daemon via:

Читайте также:  Linux сохранить настройки системы

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart 

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start 

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop 

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status 

You should really indicate the distro this is for, because these commands and paths are not correct on all distros.

Good point sgtPooki. I added a caveat explaining that my example refers to Ubuntu / Mint distributions etc. Thanks for you comment.

You can go to /etc/init.d/ - you will see a daemon template called skeleton.

You can duplicate it and then enter your script under the start function.

you may also consider running the script in background by adding '&' at the end or running it with nohup.

@LuisMuñoz how can I make it run in the background automatically. for instance when you issue /etc/init.d/mysql start, the daemon starts and runs in the background by default.

@DavidOkwii put your code in a function and run it in the background. Check my answer added to this question.

Another cool trick is to run functions or subshells in background, not always feasible though

name() < echo "Do something" sleep 1 ># put a function in the background name & #Example taken from here #https://bash.cyberciti.biz/guide/Putting_functions_in_background 

Running a subshell in the background

(echo "started"; sleep 15; echo "stopped") & 

Some commentors already stated that answers to your question will not work for all distributions. Since you did not include CentOS in the question but only in the tags, I'd like to post here the topics one has to understand in order to have a control over his/her proceeding regardless of the distribution:

  1. what is the init daemon (optional)
  2. what is the inittab file (/etc/inittab)
  3. what does the inittab file do in your distro (e.g. does it actually run all scripts in /etc/init.d ?)

For your problem, one could start the script on sysinit by adding this line in /etc/inittab and make it respawn in case it terminates:

# start and respawn after termination ttyS0::respawn:/bin/sh /path/to/my_script.sh 

The script has to be made executable in advance of course:

chmod +x /path/to/my_script.sh 

Источник

Оцените статью
Adblock
detector