File: //etc/init.d/linux-sensor
#!/bin/bash
# chkconfig: 2345 95 05
# description: Linux Sensor
### BEGIN INIT INFO
# Provides: linux-sensor
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Linux Sensor
### END INIT INFO
DAEMON=/usr/local/bin/linux-sensor
PIDFILE=/var/run/linux-sensor.pid
LOGFILE=/var/log/linux-sensor.log
resolve_pid() {
if command -v pgrep >/dev/null 2>&1; then
pgrep -f "^$DAEMON run" | head -1
else
for p in /proc/[0-9]*; do
[ -r "$p/cmdline" ] || continue
if head -c 4096 "$p/cmdline" 2>/dev/null | tr -d '\0' | grep -q "^$DAEMON run"; then
basename "$p"; break
fi
done
fi
}
start() {
P=$(resolve_pid)
if [ -n "$P" ]; then
echo "linux-sensor already running (pid $P)"
echo "$P" > "$PIDFILE"
return 0
fi
echo -n "Starting linux-sensor: "
( nohup setsid "$DAEMON" run >>"$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-sensor: "
# Don't trust just the pidfile — it can be stale or wrong (pgrep is
# camouflage-proof: cmdline is unchanged, only /proc/N/comm is).
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
# WAIT for the process to actually die. Without this, a fast `restart`
# races: the agent has SIGTERM handlers that take a moment to drain
# goroutines, so `sleep 1; start` would find the still-living agent,
# say "already running", and never spawn a new one. Then the old one
# finishes dying and nothing is left. Wait up to 15s, SIGKILL on timeout.
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-sensor is running (pid $P)"
return 0
fi
echo "linux-sensor 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