Skip to content

Instantly share code, notes, and snippets.

@jrnewell
Created July 9, 2014 19:16
Show Gist options
  • Save jrnewell/96e08cd6fcb3ad19dbf4 to your computer and use it in GitHub Desktop.
Save jrnewell/96e08cd6fcb3ad19dbf4 to your computer and use it in GitHub Desktop.
Template for init.d startup script that runs as a local user.
#! /bin/sh
### BEGIN INIT INFO
# Provides: SERVER-NAME
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the SERVER-NAME server
# Description: starts SERVER-NAME as a daemon
### END INIT INFO
NAME=SERVER-NAME
USER=james
DAEMON=/home/$USER/bin/$NAME
PID_FILE=/var/run/$USER/$NAME.pid
LOG_FILE=/var/log/$USER/$NAME.log
test -x $DAEMON || exit 0
set -e
. /lib/lsb/init-functions
make_directory() {
DIR="$1"
if [ ! -d "$DIR" ]; then
mkdir -p "$DIR"
fi
chown "$USER:$USER" $DIR
}
start_daemon() {
if [ -e "$PID_FILE" ]; then
log_action_msg "$NAME is already running" || true
return 1
fi
if [ -e "$LOG_FILE" ]; then
chown "$USER:$USER" $LOG_FILE
fi
make_directory "/var/run/$USER"
make_directory "/var/log/$USER"
su $USER -l -c "$DAEMON < /dev/null > $LOG_FILE 2>&1"
RET=$?
if [ "$RET" -ne 0 ]; then
rm -f $PID_FILE
fi
return $RET
}
kill_process() {
kill "$1"
RET=$?
if [ "$RET" -eq 0 ]; then
rm -f $PID_FILE
fi
return $RET
}
kill_daemon() {
if [ -e "$PID_FILE" ]; then
PID=`cat $PID_FILE`
if [ -n "$PID" ]; then
kill_process $PID
return $?
fi
fi
# last resort, use pgrep
PID=`pgrep -u $USER -f $DAEMON`
if [ -n "$PID" ]; then
kill_process $PID
return $?
else
log_action_msg "$NAME is not running" || true
return 1
fi
}
case "$1" in
start)
log_daemon_msg "Starting $NAME server" "$NAME" || true
start_daemon
if [ "$?" -eq 0 ]; then
log_end_msg 0 || true
else
log_end_msg 1 || true
fi
;;
stop)
log_daemon_msg "Stopping $NAME server" "$NAME" || true
kill_daemon
if [ "$?" -eq 0 ]; then
log_end_msg 0 || true
else
log_end_msg 1 || true
fi
;;
restart|force-reload)
log_daemon_msg "Restarting $NAME server" "$NAME" || true
kill_daemon
if [ "$?" -ne 0 ]; then
log_end_msg 1 || true
exit 1
fi
sleep 1
start_daemon
if [ "$?" -eq 0 ]; then
log_end_msg 0 || true
else
log_end_msg 1 || true
fi
;;
status)
status_of_proc -p $PID_FILE $DAEMON $NAME && exit 0 || exit $?
;;
*)
N=/etc/init.d/$NAME
log_action_msg "Usage: $N {start|stop|restart|force-reload|status}" || true
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment