Commits

James Sumners  committed 466fd64

Initial commit. Added the screen_daemon.sh script.

  • Participants

Comments (0)

Files changed (1)

File screen_daemon.sh

+#!/bin/bash
+# Author: James Sumners
+# License: Public Domain
+
+# To use this script, simple adjust the variables that are
+# defined before the "##### Begin Script #####" line to meet your needs.
+# Then make sure the executable bit is set on the script and add it to
+# a cron job. For example, to make sure your daemon stays running you can
+# have cron "start" it every 5 minutes:
+#
+# */5 * * * * /path/to/this/script
+#
+# You can also have the daemon start every time the machine is booted by
+# (via cron):
+#
+# @reboot /path/to/this/script
+#
+# You should also rename this script to match your daemon name. That way, you
+# can keep this template available for future use.
+
+# A name for the daemon.
+# It does not have to be the executable name.
+# When you do a `screen -ls`, this name will be shown in the list.
+DAEMON_NAME="foo"
+
+# The actual program to run as a daemon.
+# It's a good idea to specify the absolute path to the executable.
+# You can include program parameters in this string.
+DAEMON_PROGRAM="/usr/bin/yes a_parameter"
+
+# The pid file that the program will write.
+# If the program doesn't write a pid file, look for the "Cast resurrection!"
+# line in this script for an example of how to generate one for this daemon.
+PID_FILE="/var/run/${DAEMON_NAME}.pid"
+
+# Directory from which to launch the daemon program.
+# Change only if necessary.
+WORKING_DIR="${HOME}"
+
+##### Begin Script #####
+
+# Redirect all output to nowhere
+exec 2>&1
+exec 1>/dev/null
+
+# Clean up any busted screens
+screen -wipe ${DAEMON_NAME}
+
+# Check to see if screen is already running with the daemon instance
+screen -list | grep ${DAEMON_NAME}
+if [ $? -eq 0 ]; then
+	DAEMON_RUNNING=1
+else
+	DAEMON_RUNNING=0
+fi
+
+# Get a pid for daemon
+if [ -f ${PID_DIR}/${DAEMON_NAME}.pid ]; then
+	PID=$(<${PID_FILE})
+
+	# Get daemon's pulse
+	ps -p ${PID}
+
+	if [ $? -eq 0 ]; then
+		DAEMON_IS_ALIVE=1
+	else
+		DAEMON_IS_ALIVE=0
+	fi
+else
+	DAEMON_IS_ALIVE=0
+fi
+
+if [ ${DAEMON_IS_ALIVE} -eq 0 ]; then
+	# daemon is dead :(
+	if [ ${DAEMON_RUNNING} -eq 1 ]; then
+		screen -S ${DAEMON_NAME} -X quit
+	fi
+
+	# Cast resurrection!
+	screen -dmS ${DAEMON_NAME} bash -c "cd ${WORKING_DIR} && ${DAEMON_PROGRAM}"
+
+	# You can generate a pid for the previously launch program with something
+	# like the following:
+	##sleep 2 # give it time to launch
+	##PID=$(screen -ls | awk '/${DAEMON_NAME}/ {print $1}' | cut -d"." -f1)
+	##echo "${PID}" > ${PID_FILE}
+fi
+
+exit 0