Skip to content

Instantly share code, notes, and snippets.

@aleskiontherun
Last active June 10, 2022 13:24
Show Gist options
  • Save aleskiontherun/f3aab7cac4066ef28f3ce3fd0e3806d5 to your computer and use it in GitHub Desktop.
Save aleskiontherun/f3aab7cac4066ef28f3ce3fd0e3806d5 to your computer and use it in GitHub Desktop.
Pause/resume/stop process control in bash.
#!/usr/bin/env bash
TASK=$@
FAIL_CNT=0
RUN=
TASK_PID=
LOOPID=1
_ctl() {
if [[ "${RUN}" = "${1}" ]]; then
return
fi
RUN=$1
LOOPID=$((${LOOPID} + 1))
if [[ "${TASK_PID}" != "" ]]; then
kill ${TASK_PID}
wait ${TASK_PID}
TASK_PID=
fi
if [[ "${RUN}" = "true" ]]; then
_work ${LOOPID}
return
fi
if [[ "${RUN}" = "false" ]]; then
echo "Termination signal received, exiting."
fi
while [[ ${RUN} = "stop" ]]; do
sleep 1
done
}
_work() {
while [[ "${LOOPID}" = "$1" ]]; do
${TASK} &
TASK_PID=$!
echo "Process PID: ${TASK_PID}"
wait ${TASK_PID}
TASK_EXIT_CODE=$?
echo "Task exited with ${TASK_EXIT_CODE}"
if [[ "${TASK_EXIT_CODE}" = "0" ]] || [[ "${TASK_EXIT_CODE}" = "130" ]]; then
FAIL_CNT=0
else
FAIL_CNT=$((${FAIL_CNT} + 1))
printf '\033[31m%s\033[0m\n' "ACHTUNG!!! Task failed ${FAIL_CNT} times! Waiting $((2**$FAIL_CNT)) sec."
sleep $((2**${FAIL_CNT}))
fi
done
}
echo "PID: $$"
trap "_ctl 'false'" SIGINT SIGTERM
trap "_ctl 'stop'" SIGTSTP
trap "_ctl 'true'" SIGCONT
_ctl 'stop'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment