]> arthur.barton.de Git - ngircd-alex.git/blob - src/testsuite/getpid.sh
ngIRCd Release 27
[ngircd-alex.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         if [ -n "${LOGNAME:-}" ] || [ -n "${USER:-}" ]; then
27                 # Try to narrow the search down to the current user ...
28                 exec /usr/bin/pgrep $PGREP_FLAGS -n -u "${LOGNAME:-$USER}" "$1"
29         else
30                 # ... but neither LOGNAME nor USER were set!
31                 exec /usr/bin/pgrep $PGREP_FLAGS -n "$1"
32         fi
33 fi
34
35 # pidof(1) could be a good alternative on elder Linux systems
36 if [ -x /bin/pidof ]; then
37         exec /bin/pidof -s "$1"
38 fi
39
40 # fall back to ps(1) and parse its output:
41 # detect flags for "ps" and "head"
42 PS_PIDCOL=1
43 case "$UNAME" in
44         "A/UX"|"GNU"|"SunOS")
45                 PS_FLAGS="-a"; PS_PIDCOL=2
46                 ;;
47         "Haiku")
48                 PS_FLAGS="-o Id -o Team"
49                 ;;
50         *)
51                 # Linux (GNU coreutils), Free/Net/OpenBSD, ...
52                 PS_FLAGS="-o pid,comm"
53 esac
54
55 # search PID
56 ps $PS_FLAGS >procs.tmp
57 grep -v "$$" procs.tmp | grep "$1" | \
58         awk "{print \$$PS_PIDCOL}" | \
59         sort -nr >pids.tmp
60 pid=`head -1 pids.tmp`
61 rm -rf procs.tmp pids.tmp
62
63 # validate PID
64 [ "$pid" -gt 1 ] >/dev/null 2>&1 || exit 1
65
66 echo $pid
67 exit 0