blob: af32f87ea5d0a601f18f9133a74e3d5b3643e166 [file] [log] [blame]
Klement Sekera94384e42017-07-11 07:29:37 +02001#!/bin/bash
2
3rv=0
4
Andrew Yourtchenko3efd4e92021-03-04 16:56:38 +00005# 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.
9panic() {
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 Sekera94384e42017-07-11 07:29:37 +020021atexit() {
22 group_id=`ps -p $$ -o pgid=`
23 my_id=$$
24 ids=`pgrep -g $group_id -d ' ' | sed "s/\b$my_id\b//g"`
25 echo "Killing possible remaining process IDs: $ids"
26 for id in $ids
27 do
28 if ps -p $id > /dev/null
29 then
30 kill -9 $id
31 fi
32 done
Klement Sekera8712ada2017-08-16 16:38:10 +020033 exit ${rv}
Klement Sekera94384e42017-07-11 07:29:37 +020034}
35
Andrew Yourtchenko3efd4e92021-03-04 16:56:38 +000036trap "panic;" SIGINT SIGTERM
Klement Sekera94384e42017-07-11 07:29:37 +020037
Klement Sekeradb4e84c2017-08-11 10:06:15 +020038FORCE_FOREGROUND=$1
39shift
40
41source $1
42shift
43
44if [[ "${FORCE_FOREGROUND}" == "1" ]]
45then
46 $*
47else
48 $* &
Klement Sekera8712ada2017-08-16 16:38:10 +020049 pid=$!
50 wait ${pid}
Klement Sekeradb4e84c2017-08-11 10:06:15 +020051fi
52
Klement Sekera94384e42017-07-11 07:29:37 +020053rv=$?
54atexit
Klement Sekera8712ada2017-08-16 16:38:10 +020055exit ${rv}