Tom Jones | c3b416c | 2024-01-18 14:51:44 +0000 | [diff] [blame] | 1 | #!/usr/bin/env bash |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 2 | |
| 3 | rv=0 |
| 4 | |
Andrew Yourtchenko | 3efd4e9 | 2021-03-04 16:56:38 +0000 | [diff] [blame] | 5 | # Minimalist version of cleanup, used for signal handling. |
| 6 | # Sends a SIGKILL to the entire process group, including ourselves. |
| 7 | # Needs just two external commands, making it more |
| 8 | # robust in case of resource issues. |
| 9 | panic() { |
| 10 | echo "$0(pid $$): Caught a signal, emergency clean-up" |
| 11 | # use "pgid:1=" output format to get unpadded process group ID |
| 12 | group_id=`ps -p $$ -o pgid:1=` |
| 13 | echo "$0(pid $$): sending kill to process group ID:${group_id}" |
| 14 | kill -9 -- -${group_id} |
| 15 | # not reached |
| 16 | } |
| 17 | |
| 18 | # Happy camper leisurely clean up - send the signal only to other |
| 19 | # processes in the process group, and also check |
| 20 | # that the processes exists before sending the signal. |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 21 | atexit() { |
| 22 | group_id=`ps -p $$ -o pgid=` |
| 23 | my_id=$$ |
Matthew Smith | b483251 | 2024-04-02 18:27:19 +0000 | [diff] [blame] | 24 | SED=`which gsed` |
| 25 | SED=$(basename "${SED:-sed}") |
| 26 | ids=`pgrep -g $group_id -d ' ' | ${SED} "s/\b$my_id\b//g"` |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 27 | echo "Killing possible remaining process IDs: $ids" |
| 28 | for id in $ids |
| 29 | do |
| 30 | if ps -p $id > /dev/null |
| 31 | then |
| 32 | kill -9 $id |
| 33 | fi |
| 34 | done |
Klement Sekera | 8712ada | 2017-08-16 16:38:10 +0200 | [diff] [blame] | 35 | exit ${rv} |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 36 | } |
| 37 | |
Andrew Yourtchenko | 3efd4e9 | 2021-03-04 16:56:38 +0000 | [diff] [blame] | 38 | trap "panic;" SIGINT SIGTERM |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 39 | |
Klement Sekera | db4e84c | 2017-08-11 10:06:15 +0200 | [diff] [blame] | 40 | FORCE_FOREGROUND=$1 |
| 41 | shift |
| 42 | |
| 43 | source $1 |
| 44 | shift |
| 45 | |
| 46 | if [[ "${FORCE_FOREGROUND}" == "1" ]] |
| 47 | then |
| 48 | $* |
| 49 | else |
| 50 | $* & |
Klement Sekera | 8712ada | 2017-08-16 16:38:10 +0200 | [diff] [blame] | 51 | pid=$! |
| 52 | wait ${pid} |
Klement Sekera | db4e84c | 2017-08-11 10:06:15 +0200 | [diff] [blame] | 53 | fi |
| 54 | |
Klement Sekera | 94384e4 | 2017-07-11 07:29:37 +0200 | [diff] [blame] | 55 | rv=$? |
| 56 | atexit |
Klement Sekera | 8712ada | 2017-08-16 16:38:10 +0200 | [diff] [blame] | 57 | exit ${rv} |