]> arthur.barton.de Git - ngircd.git/blob - src/testsuite/getpid.sh
Test suite: simplify and enhance getpid.sh
[ngircd.git] / src / testsuite / getpid.sh
1 #!/bin/sh
2 # ngIRCd Test Suite
3 #
4 # Try to detect the PID of a running process of the current user.
5 #
6
7 set -u
8
9 # did we get a name?
10 if [ $# -ne 1 ]; then
11         echo "Usage: $0 <name>" >&2
12         exit 1
13 fi
14
15 UNAME=`uname`
16
17 # Use pgrep(1) whenever possible
18 if [ -x /usr/bin/pgrep ]; then
19         case "$UNAME" in
20                 "FreeBSD")
21                         PGREP_FLAGS="-a"
22                         ;;
23                 *)
24                         PGREP_FLAGS=""
25         esac
26         exec /usr/bin/pgrep $PGREP_FLAGS -n -u "$LOGNAME" "$1"
27 fi
28
29 # pidof(1) could be a good alternative on elder Linux systems
30 if [ -x /bin/pidof ]; then
31         exec /bin/pidof -s "$1"
32 fi
33
34 # fall back to ps(1) and parse its output:
35 # detect flags for "ps" and "head"
36 PS_PIDCOL=1
37 case "$UNAME" in
38         "A/UX"|"GNU"|"SunOS")
39                 PS_FLAGS="-a"; PS_PIDCOL=2
40                 ;;
41         "Haiku")
42                 PS_FLAGS="-o Id -o Team"
43                 ;;
44         *)
45                 # Linux (GNU coreutils), Free/Net/OpenBSD, ...
46                 PS_FLAGS="-o pid,comm"
47 esac
48
49 # search PID
50 ps $PS_FLAGS >procs.tmp
51 grep -v "$$" procs.tmp | grep "$1" | \
52         awk "{print \$$PS_PIDCOL}" | \
53         sort -nr >pids.tmp
54 pid=`head -1 pids.tmp`
55 rm -rf procs.tmp pids.tmp
56
57 # validate PID
58 [ "$pid" -gt 1 ] >/dev/null 2>&1 || exit 1
59
60 echo $pid
61 exit 0