summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuke Shumaker <LukeShu@sbcglobal.net>2013-11-02 22:55:51 -0400
committerLuke Shumaker <LukeShu@sbcglobal.net>2013-11-02 22:55:51 -0400
commit32ffdd46b945e2cad9c0d17ae40feffc6fdb4733 (patch)
tree7eaa306867429bf89167b586860594523660aef2
parent5fe5ef3d949f01ad68a3d683d6d69ffecc364fac (diff)
daemon: this is the version I've been running
-rw-r--r--daemon.sh60
1 files changed, 50 insertions, 10 deletions
diff --git a/daemon.sh b/daemon.sh
index 4952639..63def36 100644
--- a/daemon.sh
+++ b/daemon.sh
@@ -1,12 +1,52 @@
#!/bin/bash
-TMP=${TMPDIR-/tmp}/daemon
-
-running=$(pgrep -u `whoami` "$1")
-if [ -z "$running" ]; then
- mkdir -p "$TMP"
- echo "daemon: starting $1"
- nohup $@ > "$TMP/$1.out" 2> "$TMP/$1.err" &
-else
- echo "daemon: $1 is already running"
-fi
+get_ident() {
+ local pid=$1
+ ps h -o lstart -p "$pid"
+}
+
+is_running() {
+ local pidfile=$1
+ if [[ -f "$pidfile" ]]; then
+ cat "$pidfile" | while read pid ident1; do
+ ident2="$(get_ident "$pid")"
+ if [[ "$ident1" = "$ident2" ]] && [[ -n "$ident2" ]]; then
+ return 0
+ else
+ return 1
+ fi
+ done
+ else
+ return 1;
+ fi
+}
+
+main() {
+ # Parse arguments
+ if [[ $1 = '-i' ]]; then
+ shift
+ id=$1
+ shift
+ else
+ id=$1
+ fi
+
+ # Init variables
+ TMP=${TMPDIR-/tmp}/daemon
+ PIDFILE="$TMP/$id.pid"
+ OUTFILE="$TMP/$id.out"
+ ERRFILE="$TMP/$id.err"
+
+ # Run
+ if is_running "$PIDFILE"; then
+ echo "daemon: \`$id' is already running"
+ else
+ mkdir -p "$TMP"
+ echo "daemon: starting \`$id'"
+ nohup "$@" > "$OUTFILE" 2> "$ERRFILE" &
+ pid=$!
+ echo "$pid" "`get_ident $pid`" > "$PIDFILE"
+ fi
+}
+
+main "$@"