Skip to content

Commit

Permalink
Emulate pkill if it is not present
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-schulze-vireso committed Aug 7, 2022
1 parent 974d32a commit 2d22b97
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion libexec/bats-core/bats-exec-test
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,42 @@ bats_timeout_trap() {
exit 1
}

bats_get_child_processes_of() {
child_processes=()
{
read -ra header
local pid_col ppid_col
for (( i = 0; i < ${#header[@]}; ++i )); do
if [[ ${header[$i]} == "PID" ]]; then
pid_col=$i
fi
if [[ ${header[$i]} == "PPID" ]]; then
ppid_col=$i
fi
done
while read -ra row; do
if (( ${row[$ppid_col]} == parent_pid )); then
child_processes+=("${row[$pid_col]}")
fi
done
} < <(ps -ef "$parent_pid")
}

bats_kill_childprocesses_of() { # <parent-pid>
local -ir parent_pid="${1?}"
if command -v pkill; then
pkill -P "$parent_pid"
else
bats_get_child_processes_of "$parent_pid"
# kill in reverse order (latest first)
IFS=$'\n' child_processes=($(sort -r "${child_processes[@]}"))

for (( i=0; i < ${#child_processes[@]}; ++i )); do
kill "${child_processes[$i]}"
done
fi #TODO: &>/dev/null
}

# sets a timeout for this process
#
# using SIGABRT for interprocess communication.
Expand All @@ -229,7 +265,7 @@ bats_start_timeout_countdown() { # <timeout>
if kill -ABRT "$target_pid"; then
ps -ef >&3
# get rid of signal blocking child processes (like sleep)
pkill -P "$target_pid"
bats_kill_childprocesses_of "$target_pid"
else
printf "Could not signal ABRT (%d)\n" "$?" >&3
fi 2>&3
Expand Down

0 comments on commit 2d22b97

Please sign in to comment.