Skip to content

Instantly share code, notes, and snippets.

@MichaelMackus
Last active December 20, 2015 06:29
Show Gist options
  • Save MichaelMackus/6086024 to your computer and use it in GitHub Desktop.
Save MichaelMackus/6086024 to your computer and use it in GitHub Desktop.
#!/bin/sh
#
# description: This script runs a node.js instance for a specific user & application.
# The idea is to allow multiple userland node.js instances.
#
# Run with /etc/init.d/node start USERNAME [USERHOME]
# Above will launch the node.js instance in HOME/app/app.js
#
. /etc/rc.d/init.d/functions
USER=${2:-"username"}
DAEMON="/usr/bin/node"
ROOT_DIR=${3:-"/home/$USER"}
SERVER="$ROOT_DIR/app/app.js"
LOG_FILE="$ROOT_DIR/node.log"
LOCK_FILE="$ROOT_DIR/node.lock"
do_start()
{
if [ ! -f "$LOCK_FILE" ] ; then
echo -n $"Starting $SERVER: "
runuser -s /bin/sh -l "$USER" -c "$DAEMON $SERVER >> $LOG_FILE 2>&1 &"
RETVAL=$?
PID=`ps -aefw | grep "$DAEMON $SERVER" | grep -v " grep " | awk '{print $2}'`
echo
[ $RETVAL -eq 0 ] && echo "$PID" > "$LOCK_FILE"
else
echo "$SERVER is locked."
RETVAL=1
fi
}
do_stop()
{
echo -n $"Stopping $SERVER: "
pid=`cat $LOCK_FILE`
kill -9 $pid > /dev/null 2>&1 && echo_success || echo_failure
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f $LOCK_FILE
}
case "$1" in
start)
do_start
;;
stop)
do_stop
;;
restart)
do_stop
do_start
;;
*)
echo "Usage: $0 {start|stop|restart}"
RETVAL=1
esac
exit $RETVAL
}
do_stop()
{
echo -n $"Stopping $SERVER: "
pid=`ps -aefw | grep "$DAEMON $SERVER" | grep -v " grep " | awk '{print $2}'`
kill -9 $pid > /dev/null 2>&1 && echo_success || echo_failure
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f $LOCK_FILE
}
case "$1" in
start)
do_start
;;
stop)
do_stop
;;
restart)
do_stop
do_start
;;
*)
echo "Usage: $0 {start|stop|restart}"
RETVAL=1
esac
exit $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment