diff options
author | Luke Shumaker <LukeShu@sbcglobal.net> | 2013-11-02 22:55:51 -0400 |
---|---|---|
committer | Luke Shumaker <LukeShu@sbcglobal.net> | 2013-11-02 22:55:51 -0400 |
commit | 32ffdd46b945e2cad9c0d17ae40feffc6fdb4733 (patch) | |
tree | 7eaa306867429bf89167b586860594523660aef2 | |
parent | 5fe5ef3d949f01ad68a3d683d6d69ffecc364fac (diff) |
daemon: this is the version I've been running
-rw-r--r-- | daemon.sh | 60 |
1 files changed, 50 insertions, 10 deletions
@@ -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 "$@" |