]> arthur.barton.de Git - ngircd.git/blobdiff - src/testsuite/getpid.sh
Test suite: simplify and enhance getpid.sh
[ngircd.git] / src / testsuite / getpid.sh
index 8e6c63818c511ee82cabfba01508f5879cd87379..465def64605356d0c74b45a6348f7a1bcde4a8cd 100755 (executable)
@@ -1,30 +1,61 @@
 #!/bin/sh
 # ngIRCd Test Suite
-# $Id: getpid.sh,v 1.2 2002/11/10 14:28:06 alex Exp $
-
-# wurde ein Name uebergeben?
-[ $# -ne 1 ] && exit 1
-
-# Flags fuer "ps" ermitteln
-if [ `uname` = "FreeBSD" ]; then
-  PS_FLAGS="-a"; PS_PIDCOL="1"; HEAD_FLAGS="-n 1"
-elif [ `uname` = "A/UX" ]; then
-  PS_FLAGS="-ae"; PS_PIDCOL="1"; HEAD_FLAGS="-1"
-else
-  PS_FLAGS="-f"; PS_PIDCOL="2"; HEAD_FLAGS="-n 1"
-  ps $PS_FLAGS > /dev/null 2>&1
-  if [ $? -ne 0 ]; then PS_FLAGS="a"; PS_PIDCOL="1"; fi
+#
+# Try to detect the PID of a running process of the current user.
+#
+
+set -u
+
+# did we get a name?
+if [ $# -ne 1 ]; then
+       echo "Usage: $0 <name>" >&2
+       exit 1
 fi
 
-# PID ermitteln
-ps $PS_FLAGS > procs.tmp
-pid=$( cat procs.tmp | grep "$1" | awk "{print \$$PS_PIDCOL}" | sort -n | head $HEAD_FLAGS )
+UNAME=`uname`
 
-# ermittelte PID validieren
-[ "$pid" -gt 1 ] > /dev/null 2>&1
-[ $? -ne 0 ] && exit 1
+# Use pgrep(1) whenever possible
+if [ -x /usr/bin/pgrep ]; then
+       case "$UNAME" in
+               "FreeBSD")
+                       PGREP_FLAGS="-a"
+                       ;;
+               *)
+                       PGREP_FLAGS=""
+       esac
+       exec /usr/bin/pgrep $PGREP_FLAGS -n -u "$LOGNAME" "$1"
+fi
+
+# pidof(1) could be a good alternative on elder Linux systems
+if [ -x /bin/pidof ]; then
+       exec /bin/pidof -s "$1"
+fi
+
+# fall back to ps(1) and parse its output:
+# detect flags for "ps" and "head"
+PS_PIDCOL=1
+case "$UNAME" in
+       "A/UX"|"GNU"|"SunOS")
+               PS_FLAGS="-a"; PS_PIDCOL=2
+               ;;
+       "Haiku")
+               PS_FLAGS="-o Id -o Team"
+               ;;
+       *)
+               # Linux (GNU coreutils), Free/Net/OpenBSD, ...
+               PS_FLAGS="-o pid,comm"
+esac
+
+# search PID
+ps $PS_FLAGS >procs.tmp
+grep -v "$$" procs.tmp | grep "$1" | \
+       awk "{print \$$PS_PIDCOL}" | \
+       sort -nr >pids.tmp
+pid=`head -1 pids.tmp`
+rm -rf procs.tmp pids.tmp
+
+# validate PID
+[ "$pid" -gt 1 ] >/dev/null 2>&1 || exit 1
 
 echo $pid
 exit 0
-
-# -eof-