Skip to content

Commit

Permalink
Kill child process if we are killed
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanhb committed Jun 14, 2019
1 parent caa3090 commit 4fe3651
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion src/kcptun
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@
# use sh rather than bash in order to work correctly on router device which has no bash installed.
set -e

child_pid=

func_trap() {
local signal="$1"
# we can't kill background child process with signal INT
if [[ "$signal" == INT ]]; then signal=TERM; fi
if [[ -n "$child_pid" ]]; then
kill -s "$signal" "$child_pid" || true
fi
}

trap_with_arg() {
local func sig
func="$1"
shift
for sig ; do
trap "$func $sig" "$sig"
done
}

has_builtin() {
[[ "$(command -v "$1")" == "$1" ]]
}

execute() {
local type bin key0 value0 key1 value1

Expand Down Expand Up @@ -130,7 +154,29 @@ execute() {
fi

unset SS_LOCAL_HOST SS_LOCAL_PORT SS_REMOTE_HOST SS_REMOTE_PORT SS_PLUGIN_OPTIONS
"$bin" "$key0" "$value0" "$key1" "$value1" "$@"
if has_builtin wait && has_builtin trap && has_builtin kill; then
"$bin" "$key0" "$value0" "$key1" "$value1" "$@" &
child_pid=$!
if [[ -z "$child_pid" ]]; then
echo Unknown error occur, cannot get process id of child process. >&2
exit 1
fi
# Send all signal to kcptun
trap_with_arg func_trap HUP INT QUIT ILL TRAP ABRT BUS FPE USR1 SEGV USR2 PIPE ALRM TERM
local wait_result=0
while true; do
local value=0
wait "$child_pid" 2>/dev/null || value=$?
# 127 means this pid is not child process of our shell.
if [[ "$value" == 127 ]]; then break; fi
wait_result="$value"
if [[ "$value" == 0 ]]; then break; fi
done
child_pid=
return $wait_result
else
"$bin" "$key0" "$value0" "$key1" "$value1" "$@"
fi
}

findBinary
Expand Down

0 comments on commit 4fe3651

Please sign in to comment.