diff --git a/src/procmon.bash b/src/procmon.bash index e4b0a2f..51ddff2 100644 --- a/src/procmon.bash +++ b/src/procmon.bash @@ -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}") diff --git a/test/test_procmon.bats b/test/test_procmon.bats index 9a7efcf..ad7cfc2 100644 --- a/test/test_procmon.bats +++ b/test/test_procmon.bats @@ -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" ] +}