How to run my looping Bash script as a service? - linux

I have 2 Amazon Linux EC2 instances that are running HAProxy. I want to monitor each instance from the other instance and if a instance becomes unavailable, the other instance will issue a API command to move the elastic IP to the active server.
I created a Bash script to do the monitoring every XX seconds. I need to set the script to run as a service so I created a service wrapper and placed in /etc/init.d based on a template that I found and registered as a service.
The problem is when I issue command #service hamonitor start, it says "Starting hamonitor...", but I never see the OK message and if I issue the stop command, it fails and if I issue the status command, it says it is not running. But, if I check the logs, it shows that the script is in fact running. I assume that I need a proper PID file and/or since the script runs in a infinite loop, it never completes so the OK does not get issued.
Service Wrapper:
#!/bin/sh
#
# /etc/init.d/hamonitor
# Subsystem file for "hamonitor" server
#
# chkconfig: 2345 95 05 (1)
# description: hamonitor server daemon
#
# processname: hamonitor
### BEGIN INIT INFO
# Provides:
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:
# Short-Description:
# Description:
### END INIT INFO
# source function library
. /etc/rc.d/init.d/functions
PROG=hamonitor
EXEC=/etc/haproxy/hamonitor
LOCKFILE=/var/lock/subsys/$prog
PIDFILE=/var/run/$prog.pid
RETVAL=0
start() {
echo -n $"Starting $PROG:"
echo
#daemon $EXEC &
/etc/haproxy/hamonitor &
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
touch LOCKFILE
touch PIDFILE
echo "[ OK ]"
else
echo "[ FAIL: ${retval} ]"
fi
return $RETVAL
}
stop() {
echo -n $"Stopping $PROG:"
echo
killproc $PROG -TERM
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
rm -f LOCKFILE
rm -f PIDFILE
echo "[ OK ]"
else
echo "[ FAIL: ${RETVAL} ]"
fi
return $RETVAL
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $PROG
RETVAL=$?
;;
restart)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|status|restart}"
RETVAL=1
esac
exit $RETVAL
App:
#!/usr/bin/env bash
export EC2_HOME=/opt/aws/apitools/ec2
export JAVA_HOME=/usr/lib/jvm/jre
AWS_ACCESS_KEY="XXXXXXXXXXXXXXXXXXXXXXXXX"
AWS_SECRET_KEY="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
VIP1="1.2.3.4"
VIP1_ALLOCATIONID="eipalloc-XXXXXXX"
THIS_NODE_EC2_ID="i-XXXXXXX"
THIS_NODE_PRIVATE_IPADDRESS1="10.60.0.11"
THIS_NODE_HEALTHCHECK_URL="http://10.60.0.10/haproxy?monitor"
OTHER_NODE_HEALTHCHECK_URL="http://10.60.49.50/haproxy?monitor"
CHECK_OTHER_INTERVAL=5
CHECK_OTHER_FAIL_COUNT=0
CHECK_OTHER_RUN_COUNT=0
AFTER_TAKEOVER_WAIT=30
function takeover_vips {
/opt/aws/bin/ec2-associate-address -aws-access-key ${AWS_ACCESS_KEY} -aws-secret-key ${AWS_SECRET_KEY} -a ${VIP1_ALLOCATIONID} -i ${THIS_NODE_EC2_ID} -private-ip-address ${THIS_NODE_PRIVATE_IPADDRESS1} -allow-reassociation > /dev/null
}
function does_this_node_have_ips {
is_active=$(/opt/aws/bin/ec2-describe-addresses -aws-access-key ${AWS_ACCESS_KEY} -aws-secret-key ${AWS_SECRET_KEY} | grep ${VIP1} | grep ${THIS_NODE_EC2_ID})
if [ "$is_active" = "" ]; then
echo "no"
else
echo "yes"
fi
}
function log_msg {
msg=$1
msg="$(date) -- ${msg}"
echo ${msg} >> /var/log/hamonitorlog
}
while [ . ]; do
healthcheck_response=$(curl -sL -w "%{http_code}" ${OTHER_NODE_HEALTHCHECK_URL} -o /dev/null)
if [ "$healthcheck_response" != "200" ]; then
CHECK_OTHER_FAIL_COUNT=$((CHECK_OTHER_FAIL_COUNT+1))
if [ "$CHECK_OTHER_FAIL_COUNT" -gt 2 ]; then
takeover_vips
CHECK_OTHER_FAIL_COUNT=0
sleep ${AFTER_TAKEOVER_WAIT}
fi
sleep ${CHECK_OTHER_INTERVAL}
done

Some Linux distribution have up-start and other init; I assume you have init. The chkconfig is being used to maintain symlinks. You should confirm the comment,
# chkconfig: 2345 95 05 (1)
is correct for your system.
As a guess, you need daemon to be invoked via a script. This may have been a script function in some init script library, like /etc/rc.d/init.d/functions. I would suggest that you use the daemon() function if it exists. Either,
daemon $EXEC & #option1
nohup /etc/haproxy/hamonitor < /dev/null > /dev/null 2>&1 & #option2
/etc/haproxy/hamonitor& #option3, 2 lines.
disown $! #...
This is related to SIGCHLD and process return status (see man wait for more). As well, you may need to detach hamonitor from the controlling terminal. You can use logger to send information to the system logs in this case; I guess the App script is the hamonitor code? Just change echo to logger.
If the hamonitor needs stdout, stdin, and/or stderr, you may need to redirect to some other file if it requires it. You might also consider running it via screen if this is the case.
Edit: The last option can be used to create a proper PIDFILE. For instance,
# !!! optional grabbing of lock here...
/etc/haproxy/hamonitor & # spawn in bg
HA_PID=$! # record spawn pid
echo $HA_PID > $PIDFILE # record the PID to a file for `stop`.
# !!! optional release of lock here...
disown $HA_PID # detach script from terminal.
Services should never use echo and the like; logger is the better option. This is probably not your issue unless hamonitor tries to read from something. Mainly the issue is that start() will wait for the hamonitor to finish if you don't disown, so the rc script's start will never finish.
Generically, you can look at /etc/rc.d/init.d/functions, provide a link to your file, or provide your distribution and version (or at least linux standard base conformance which seems to define how this should work in its different versions). The file can be different on each and every Linux. You can look at this file yourself if you understand scripting to see what environment variables, files, etc are expected and what functions you use in this file. For instance, killproc is most likely defined there.

Related

Service that uses libcurl not auto-starting on Debian?

I've written and compiled a daemon program in C which is meant to run in the background with root access. My program uses libcurl to make some occasional network calls. I've also written a simple init.d script to govern its startup and shutdown procedures. I would like this service to automatically start on boot, and based on what I've done I would expect it to already be doing this. However, I'm noticing an error in the logs relating to libcurl, and as a result the service is not being started automatically.
My program is located in /usr/bin/myprog and I have the following bash script located in /etc/init.d/myprog:
#!/bin/bash
### BEGIN INIT INFO
# Provides: myprog
# Required-Start: $remote_fs $network $syslog
# Required-Stop: $remote_fs $network $syslog
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: myprog
# Description: My Daemon Program
### END INIT INFO
. /lib/lsb/init-functions
SCRIPT=/usr/bin/myprog
PIDFILE=/var/run/myprog.pid
start() {
if [ -f $PIDFILE ]; then
echo "Service is already started"
return 2
else
$SCRIPT
$RETVAL="$?"
return "${RETVAL}"
fi
}
stop() {
if [ -f $PIDFILE ]; then
kill $(cat $PIDFILE)
rm -f $PIDFILE
return 0
else
echo "Service is not running"
return 2
fi
}
case "$1" in
start)
log_daemon_msg "Starting myprog" "myprog"
start
;;
stop)
log_daemon_msg "Stopping myprog" "myprog"
stop
;;
status)
status_of_proce "$SCRIPT" "myprog" && exit 0 || exit $?
;;
restart)
log_daemon_msg "Restarting myprog" "myprog"
stop
start
;;
*)
echo $"Usage: $0 {start|stop|status|restart}" >&2
exit 3
;;
esac
I then ran sudo update-rc.d myprog defaults and this created the following files:
/etc/rc0.d/K01myprog
/etc/rc1.d/K01myprog
/etc/rc2.d/K01myprog
/etc/rc3.d/S02myprog
/etc/rc4.d/S02myprog
/etc/rc5.d/S02myprog
/etc/rc6.d/K01myprog
And as far as I can tell, each of those 7 files are identical copies of the one I posted above. Based on the various tutorials and forums I've been reading, I would think this would be sufficient. However, my service does not appear to be auto-starting on boot. If I call sudo /etc/init.d/myprog start directly, then it starts up fine. But otherwise it does not appear to be launched.
I then noticed an error message in the logs which said "curl error: could not resolve host," even though the particular host it was referencing was definitely valid. So I think perhaps it's trying to launch my application before something that libcurl needs is ready, and is therefore failing to launch. Again, if I launch it manually it works fine. How can I fix this?
If DNS resolution is the point of failure then use the IP address instead. If you are unwilling to use the IP address, add the hostname and IP address to /etc/hosts.

echo message not coming on terminal with systemd

I have systemd service, say xyzWarmup.service.
Here is the service file
[Unit]
Description=Xyz agent.
After=fooAfter.service
Before=fooBefore1.service
Before=fooBefore2.service
[Service]
# During boot the xyz.sh script reads input from /dev/console. If the user
# hits <ESC>, it will skip waiting for xyz and abc to startup.
Type=oneshot
StandardInput=tty
StandardOutput=tty
ExecStart=/usr/bin/xyz.sh start
RemainAfterExit=True
ExecStop=/usr/bin/xyz.sh stop
[Install]
WantedBy=multi-user.target
Following is the part of xyz.sh.
#! /bin/bash
#
### BEGIN INIT INFO
# Required-Stop: Post
### END INIT INFO
XYZ=/usr/bin/Xyz
prog="Xyz"
lockfile=/var/lock/subsys/$prog
msg="Completing initialization"
start() {
# Run wfw in background
ulimit -c 0
# wfw has a default timeout of 10 minutes - just pick a large value
wfw -t 3600 xyz abc >/dev/null 2>&1 &
PID=$!
# Display the message here after spawning wfw so Esc can work
echo -n $"$msg (press ESC to skip): "
while [ 1 ]; do
read -s -r -d "" -N 1 -t 0.2 CHAR || true
if [ "$CHAR" = $'\x1B' ]; then
kill -9 $PID 2>/dev/null
# fall through to wait for process to exit
fi
STATE="`ps -p $PID -o state=`"
if [ "$STATE" = "" ]; then
# has exited
wait $PID 2>/dev/null
if [ $? -eq 0 ]; then
echo "[ OK ]"
echo
exit 0
else
echo "[ FAILED ]"
echo "This is failure"
exit 1
fi
fi
done
}
When this script runs during boot I see the following message coming from the script
Completing initialization (press ESC to skip):
Updated:
This is the additional output which I see after the previous line
[[ OK ] Started Xyz agent.\n'
If you carefully see, there are 2 opening square brackets( '[' ), from this it looks like that systemd is overwriting the log messages. The first "[" comes from the initscript's "[ OK ]". Can somebody explain this better ?
I don't see "[ OK ]" or "[ FAILED ]" on my screen.
When I was using this script as initscript in Fedora14, I used to see these messages. Once, I have shifted to systemd. I have started seeing this issue.
systemd version is : systemd-201-2.fc18.9.i686 and systemd.default_standard_output=tty
Kindly help.
It looks to me that your issue here is that the script is never getting attached to the TTY. The output is showing up because you have that hard-coded to go to /dev/console in your script. With StandardInput=tty, systemd waits until the tty is available, and it's probably already in use. Your script is just sitting there not connected to input in the infinite loop. You could try StandardInput=tty-force, and I bet that will work, although I'm not sure what else that might break.
Personally, I think I might go back and rethink the approach entirely. It sounds like you want the boot to entirely block on this service, but let you skip by hitting escape. Maybe there's a better way?

How to get this init.d script to start at server restart?

I'm following the directions on installing Redis on a production machine (CentOS using chkconfig).
The example script I was given requires the argument start to actually start it, which it seems init.d does not do (pass arguments).
The real command that must be run is /etc/init.d/redis_6379 start, but what its actually calling is /etc/inti.d/redis_6379, which simply says use start or stop as an argument
Therefor, when my server reboots it doesnt actually start redis. What should I do here?
Here is the initial config
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
#
# chkconfig: - 85 15
# description: Redis is a persistent key-value database
# processname: redis_6379
REDISPORT=6379
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
PIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/etc/redis/${REDISPORT}.conf"
case "$1" in
start)
if [ -f $PIDFILE ]
then
echo "$PIDFILE exists, process is already running or crashed"
else
echo "Starting Redis server..."
$EXEC $CONF
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping ..."
$CLIEXEC -p $REDISPORT shutdown
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
;;
*)
echo "Please use start or stop as first argument"
;;
esac
Make sure your script is added for service management by chkconfig. Use chkconfig --list to see the list and use chkconfig --add scriptname if it's not there. After that configure the runlevels you want it to be called into. I would guess it's 3, 4 and 5 so: chkconfig --level 345 scriptname on.
You should tell us how exactly you are running the script from init.d
But here is a dirty workaround:
Change the line
start)
to
start|'')
This will make it start if there are no parameters passed.
If you want to start a service through command line you can just add in /etc/rc.d/rc.local too for the same instead of creating a service file in init.d.
Centos redis has an init script with a chkconfig header line stating that it will start in all runlevels, which is very bad. chkconfig is used to manage the symlinks in /etc/rc.d
# chkconfig: - 85 15
I suggest that redis is a service to run in level 3 after critical services have launched (sshd for instance). In your test scenario's reboot your server before going to production. If redis cannot launch (just happened here) you cannot boot it in another runlevel to fix it.
If you implement the proper headers you can use init and also systemd (Fedora)
Your should add code below to the script /etc/inti.d/redis_6379. The status argument is used by command service --status-all.
# processname: redis_6379
# Source function library.
. /etc/init.d/functions
...
case "$1" in
status)
status -p $PIDFILE redis
script_result=$?
;;
Init.d's days are numbered, wtf are you still reading this for? There's no more sudo service, all the new kids are slapping down syscrtl
Nowadays like of course on my ubuntu 17.04 server at work, /etc/rc.local didn't even exist
Just write a new one!
rc.local is awesome, especially combined with the unix style daemonize program... those two alone, I can pretty much call it a day.
However, if you want to take rc.local to the next level, I'll cover basic ideas behind my own personal redis init.d script--same one we use on production servers across my company:
pre-empt redis complaint about system socket/file limits
slap in some linux perf and mess around with sysconf in persistent fashion
autopilot redis while i go take a nap
#!/bin/sh
### BEGIN INIT INFO
# Provides: redis
# Required-Start: $syslog
# Required-Stop: $syslog
# Should-Start: $all
# Should-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: start and stop redis
# Description: persistent key-value db
### END INIT INFO
NAME=redis
PATH=/opt/bin:/opt/sbin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
EXEC=/opt/sbin/redis-server
CLIEXEC=/opt/sbin/redis-cli
CONF=/etc/$NAME/$NAME.conf
PIDFILE=/var/run/$NAME.pid
SOCKET=/var/run/$NAME.sock
PERF=/tmp/redis.sysctl
KERNELPG=/sys/kernel/mm/transparent_hugepage/enabled
[ -x /opt/sbin/redis-server ] || exit 0
set -e
# tune system for better redis performance
if [ ! -f $PERF ]; then
echo "tunning redis..." &>> $PERF
echo never > $KERNELPG && cat $KERNELPG &>> $PERF
sysctl -w net.core.somaxconn=65535 &>> $PERF
sysctl -w vm.overcommit_memory=1 &>> $PERF
echo "tuned." &>> $PERF && cat $PERF
fi
next, if we're doin' it right:
let's have nice idiomatic case $money numbers, focused on starting and stopping without sorting through excessive PID tracking shenanigans
take advantage of the start-stop-daemon (i.e. can't get cut short by parent process death if there is no parent process)
case $1 in
start)
if [ ! -f $PIDFILE ]; then
echo -n "Starting $NAME: "
start-stop-daemon --start --pidfile $PIDFILE --exec $EXEC -- $CONF
echo "waiting for redis db to start..."
while [ ! -f $PIDFILE ]; do
sleep 0.1;
done
fi
PID=$(cat $PIDFILE)
echo "running with pid: $PID"
;;
stop)
if [ ! -f $PIDFILE ]; then
echo "redis is already stopped"
else
PID=$(cat $PIDFILE)
echo -n "Stopping $NAME: "
$CLIEXEC -s $SOCKET shutdown
echo "waiting for shutdown..."
while [ -x /proc/${PID} ]; do
sleep 0.1
done
echo "db stopped."
fi
;;
status)
if [ -f $PIDFILE ]; then
PID=$(cat $PIDFILE)
echo "running with pid: $PID"
else
echo "stopped."
fi
;;
restart|force-reload)
$0 stop && $0 start
;;
*)
echo "Argument \"$1\" not implemented."
exit 2
;;
esac
exit 0
edit redis.conf to designate daemonize yes. Make redis the primary responsible party for administrative PID file state (in case you were wondering why we didn't have to do anything with it in the script, except read from it if it's around)
mkdir /etc/redis
echo 'daemonize yes' >> /etc/redis/redis.conf
echo 'pidfile /var/run/redis.pid' >> /etc/redis/redis.conf
update your rc entry by name after copying and setting execution bits:
mkdir /etc/redis
vim /etc/redis/redis # keep it traditional, no .sh extensions here
# saving buffers from root all damn day...
chmod a+x /etc/init.d/redis
update-rc.d redis defaults
Here's the full example link w/ service installer. Again, be sure to edit conf and install to suit you. Most people would probably want to remove the listening file path in favor of TCP stack w/ redis port number open for client(s),

Adding a service startup script for Amazon linux AMI

I am using an Amazon Linux AMI and doing some custom modifications(added an axis2server, etc) on it and saving it as a new AMI. Now what I want to do is when the AMI boots up, start up axis2server(ie.axis2server should automatically start when the instance boots up). For that I used a init script like below and ran the following command:
chkconfig --add axisservice
But when I launch a new instance from my image, the axis2server is not getting started.
I just only need to execute the script /home/ec2-user/axis2-1.6.1/bin/axis2server.sh at startup. Am I missing anything here?
#! /bin/sh
# Basic support for IRIX style chkconfig
###
# chkconfig: 235 98 55
# description: Manages the services you are controlling with the chkconfig command
###
case "$1" in
start)
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh &
echo "."
;;
stop)
echo -n "Stopping axisservice"
echo "."
;;
*)
echo "Usage: /sbin/service axisservice {start|stop}"
exit 1
esac
exit 0
I went through https://help.ubuntu.com/community/CloudInit as well and it provides a mechanism called User-Data Scripts, where a user can execute a script when launching the script.
$ euca-run-instances --key mykey --user-data-file myscript.sh ami-axxxx
This is a command line option and what I want is something like when I launch the instance through the UI, the script should be started.Therefore, I think the above option can not be used in my case. Please correct me if I am wrong.
Thanks,
H.
I bet the environment is not set(up correctly). This means that I am guessing that your shell script tries to start another program and it's not to be found.
So at first, I'd adjust the start part of your script (current):
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh &
echo "."
Edited:
echo -n "Starting axisservice"
touch ~/temp.txt
cd /home/ec2-user/axis2-1.6.1/bin
./axis2server.sh
RETVAL=$?
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
echo "."
So what did I do?
removed & so script waits for your shell script (axis2server.sh) to complete
checked the return status ($?) of your shell script
Further debugging:
Add set -x to your scripts to enable tracing and log both stderr and stdout.
Questions:
Are you are aware that stop (in your service script) doesn't do anything?
touch ~/temp.txt is that supposed to create /root/temp.txt? (I'm guessing root runs this script.)
If none of my suggestions work, can you share axis2server.sh and paste stderr and stdout?

How can I run a Perl script as a system daemon in linux?

What's a simple way to get a Perl script to run as a daemon in linux?
Currently, this is on CentOS. I'd want it to start up with the system and shutdown with the system, so some /etc/rc.d/init.d integration would also be nice, but I could always add a custom line to /etc/rc.d/rc.local.
The easiest way is to use Proc::Daemon.
#!/usr/bin/perl
use strict;
use warnings;
use Proc::Daemon;
Proc::Daemon::Init;
my $continue = 1;
$SIG{TERM} = sub { $continue = 0 };
while ($continue) {
#do stuff
}
Alternately you could do all of the things Proc::Daemon does:
Fork a child and exits the parent process.
Become a session leader (which detaches the program from the controlling terminal).
Fork another child process and exit first child. This prevents the potential of acquiring a controlling terminal.
Change the current working directory to "/".
Clear the file creation mask.
Close all open file descriptors.
Integrating with the runlevel system is easy. You need a script like the following (replace XXXXXXXXXXXX with the Perl script's name, YYYYYYYYYYYYYYYYYYY with a description of what it does, and /path/to with path to the Perl script) in /etc/init.d. Since you are using CentOS, once you have the script in /etc/init.d, you can just use chkconfig to turn it off or on in the various runlevels.
#!/bin/bash
#
# XXXXXXXXXXXX This starts and stops XXXXXXXXXXXX
#
# chkconfig: 2345 12 88
# description: XXXXXXXXXXXX is YYYYYYYYYYYYYYYYYYY
# processname: XXXXXXXXXXXX
# pidfile: /var/run/XXXXXXXXXXXX.pid
### BEGIN INIT INFO
# Provides: $XXXXXXXXXXXX
### END INIT INFO
# Source function library.
. /etc/init.d/functions
binary="/path/to/XXXXXXXXXXXX"
[ -x $binary ] || exit 0
RETVAL=0
start() {
echo -n "Starting XXXXXXXXXXXX: "
daemon $binary
RETVAL=$?
PID=$!
echo
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/XXXXXXXXXXXX
echo $PID > /var/run/XXXXXXXXXXXX.pid
}
stop() {
echo -n "Shutting down XXXXXXXXXXXX: "
killproc XXXXXXXXXXXX
RETVAL=$?
echo
if [ $RETVAL -eq 0 ]; then
rm -f /var/lock/subsys/XXXXXXXXXXXX
rm -f /var/run/XXXXXXXXXXXX.pid
fi
}
restart() {
echo -n "Restarting XXXXXXXXXXXX: "
stop
sleep 2
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status XXXXXXXXXXXX
;;
restart)
restart
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
;;
esac
exit 0
If you don't have Proc::Daemon as suggested by Chas. Owens, here's how you'd do it by hand:
sub daemonize {
use POSIX;
POSIX::setsid or die "setsid: $!";
my $pid = fork() // die $!; #//
exit(0) if $pid;
chdir "/";
umask 0;
for (0 .. (POSIX::sysconf (&POSIX::_SC_OPEN_MAX) || 1024))
{ POSIX::close $_ }
open (STDIN, "</dev/null");
open (STDOUT, ">/dev/null");
open (STDERR, ">&STDOUT");
}
I think the easiest way is to use daemon. It allows you to run any process as a daemon. This means you don't have to worry about libraries if you, for example, decided to change to python. To use it, just use:
daemon myscript args
This should be available on most distros, but it might not be installed by default.
I used supervisor for running a perl script.
As a system administrator, I like to minimise changes and variations among server and like to stick to core services or bare minimum.
Supervisor was already installed and available for a python-flask application
running on the same box. So, I just added a conf file for the perl script I wanted to run as a service. Now, I can do
supervisorctl start/stop/restart my_perl_script_supervisor_service_name

Resources