File: //etc/init.d/linux-monitor
#!/bin/bash
# chkconfig: 2345 96 04
# description: Linux Monitor
### BEGIN INIT INFO
# Provides: linux-monitor
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Linux Monitor
### END INIT INFO
DAEMON=/usr/local/bin/linux-monitor
PIDFILE=/var/run/linux-monitor.pid
LOGFILE=/var/log/linux-monitor.log
resolve_pid() {
if command -v pgrep >/dev/null 2>&1; then
pgrep -f "^$DAEMON\$" | head -1
else
for p in /proc/[0-9]*; do
[ -r "$p/cmdline" ] || continue
first=$(head -c 4096 "$p/cmdline" 2>/dev/null | tr '\0' '\n' | head -1)
[ "$first" = "$DAEMON" ] && basename "$p" && break
done
fi
}
start() {
P=$(resolve_pid)
if [ -n "$P" ]; then
echo "linux-monitor already running (pid $P)"
echo "$P" > "$PIDFILE"
return 0
fi
echo -n "Starting linux-monitor: "
( nohup setsid "$DAEMON" >>"$LOGFILE" 2>&1 < /dev/null & ) >/dev/null 2>&1
sleep 1
P=$(resolve_pid)
if [ -n "$P" ]; then
echo "$P" > "$PIDFILE"
echo "OK (pid $P)"
else
echo "FAILED (see $LOGFILE)"
return 1
fi
}
stop() {
echo -n "Stopping linux-monitor: "
P=$(resolve_pid)
if [ -z "$P" ] && [ -f "$PIDFILE" ]; then
P=$(cat "$PIDFILE" 2>/dev/null)
if [ -n "$P" ] && ! [ -r "/proc/$P/cmdline" ]; then P=""; fi
fi
if [ -n "$P" ]; then
kill "$P" 2>/dev/null
# See linuxmdm-agent.init for why we WAIT instead of trusting `sleep 1`.
i=0
while [ -d "/proc/$P" ] && [ $i -lt 15 ]; do
sleep 1
i=$((i + 1))
done
[ -d "/proc/$P" ] && kill -9 "$P" 2>/dev/null
fi
rm -f "$PIDFILE"
echo "OK"
}
status() {
P=$(resolve_pid)
if [ -n "$P" ]; then
echo "linux-monitor is running (pid $P)"
return 0
fi
echo "linux-monitor is not running"
return 3
}
case "$1" in
start) start;;
stop) stop;;
restart) stop; sleep 1; start;;
status) status;;
*) echo "Usage: $0 {start|stop|restart|status}"; exit 2;;
esac