Created
July 5, 2013 09:34
-
-
Save sebble/5933319 to your computer and use it in GitHub Desktop.
A script to run any executable in background, check if it is already running, or kill the process tree (includes children spawned from main executable).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# simple service checker, starter, process tree killer | |
# usage: | |
# init.sh <script_path> [start|stop|status|restart] | |
SCRIPT=$1 | |
ACTION=$2 | |
BASENAME=$(basename $SCRIPT) | |
NAME=$BASENAME | |
GROUPPID=$(ps x -o "%r %c" | grep -v grep | grep -v init | grep $BASENAME | awk '{print "-" $1}') | |
RUNNING="$(ps aux | grep -v grep | grep -v cron/init | grep -c $BASENAME)" | |
STOP="kill -TERM $GROUPPID" | |
## uncommment this for logging | |
#LOGFILE="/var/log/initsh/$(basename $SCRIPT).log" | |
#ERRFILE="/var/log/initsh/$(basename $SCRIPT).err" | |
#mkdir -p /var/log/initsh | |
## commment this for logging | |
LOGFILE="/dev/null" | |
ERRFILE="/dev/null" | |
case "$ACTION" in | |
"start") | |
if [ "$RUNNING" -eq "0" ]; then | |
echo "Init: Starting $NAME" | |
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE & | |
else | |
echo "Init: $NAME is running" | |
fi | |
;; | |
"stop") | |
if [ "$RUNNING" -eq "0" ]; then | |
echo "Init: $NAME is NOT running"; | |
else | |
echo "Init: Stopping $NAME" | |
$STOP | |
fi | |
;; | |
"status") | |
if [ "$RUNNING" -eq "0" ]; then | |
echo "Init: $NAME is NOT running"; | |
else | |
echo "Init: $NAME is running" | |
fi | |
;; | |
"restart") | |
if [ "$RUNNING" -eq "0" ]; then | |
echo "Init: Starting $NAME" | |
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE & | |
else | |
echo "Init: Stopping $NAME" | |
$STOP | |
echo "Init: Starting $NAME" | |
$SCRIPT 1>> $LOGFILE 2>> $ERRFILE & | |
fi | |
;; | |
*) | |
# do nothing (help) | |
echo "usage:" | |
echo " $0 <script_path> [start|stop|status|restart]" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes:
pidof -x $BASENAME
to check status?