feat: add process lifecycle callback to procmon

This commit is contained in:
gmega 2025-06-20 15:42:34 -03:00
parent 32406ce934
commit cead3935f8
No known key found for this signature in database
GPG Key ID: 6290D34EAD824B18
2 changed files with 57 additions and 2 deletions

View File

@ -17,6 +17,8 @@ source "${LIB_SRC}/utils.bash"
_pm_output=$(clh_output_folder "pm")
_pm_pid=""
declare -A _pm_callbacks
_pm_init_output() {
rm -rf "${_pm_output}" || true
mkdir -p "${_pm_output}"
@ -229,14 +231,44 @@ pm_list_descendants() {
}
pm_async() {
proc_type=""
command=()
while [[ "$#" -gt 0 ]]; do
case "$1" in
-%-)
shift
proc_type="$1"
break
;;
*)
command+=("$1")
shift
;;
esac
done
(
"$@"
pm_job_exit "$?"
"${command[@]}"
exit_code=$?
if [ -n "$proc_type" ]; then
# calls the callback for this proc type
if [ -n "${_pm_callbacks[$proc_type]}" ]; then
"${_pm_callbacks[$proc_type]}" "$proc_type" "$BASHPID" "$exit_code"
fi
fi
pm_job_exit "$exit_code"
) &
pm_track_last_job
echo $!
}
pm_register_callback() {
_pm_assert_state_not "running" || return 1
local proc_type="$1" callback="$2"
_pm_callbacks[$proc_type]="$callback"
}
_pm_list_descendants() {
local parent="$1"
result+=("${parent}")

View File

@ -162,3 +162,26 @@ setup() {
assert_equal "$(pm_state)" "halted"
}
@test "should call lifecycle callbacks when processes start and stop" {
callback() {
local proc_type="$1" pid="$2" exit_code="$3"
touch "${_pm_output}/${pid}-${proc_type}-${exit_code}"
}
pm_register_callback "sleepy" "callback"
pm_start
pid1=$(pm_async sleep 0.1 -%- "sleepy")
pid2=$(pm_async sleep 0.1 -%- "sleepy")
await "$pid1"
await "$pid2"
pm_stop
assert_equal "$(pm_state)" "halted"
assert [ -f "${_pm_output}/${pid1}-sleepy-0" ]
assert [ -f "${_pm_output}/${pid2}-sleepy-0" ]
}