Skip to content

Instantly share code, notes, and snippets.

@boppy
Created June 10, 2019 16:38
Show Gist options
  • Save boppy/fce0937ba8be573222d3ef875f10fc38 to your computer and use it in GitHub Desktop.
Save boppy/fce0937ba8be573222d3ef875f10fc38 to your computer and use it in GitHub Desktop.
Run a bash script with soft timeout

This little shell boilerplate can be used to run a long running program that has a custom exit state if a timeout is reached. Usefull to monitor by exit state.

The script basically sleeps for the allowed lifetime and touches a file if the parent process is still running. The running process IS NOT INTERUPTED, but after it finished a pre-defined exit state is retuned by the script if timeout was reached.

Config

  • Define exit code in line :4
  • optionally define lifetime in line :7
  • optionally define temp file in line :10
  • Insert long running code and delete lines :30 and :31
  • optionally correct placement of default exit code from line :36
  • optionally apply more logic if timeout is reached at line :44
  • optionally apply more logic if timeout is NOT reached at line :48
#!/usr/bin/env bash
# timeout exit state
to_exit=214
# lifetime in seconds
lifetime=2
# path of temp file ($$ evaluates to current PID)
tmp_name="/tmp/timelimit-$$"
# Remove tracking file if existing
[[ -f "$tmp_name" ]] && rm -f "$tmp_name"
# Parameters: LIFETIME_IN_SECONDS FILENAME_TO_TOUCH PPID_OF_PROCESS_TO_CHECK
function sleep_n_touch {
# sleep
sleep $1
# if process is still running, touch a file
ps -p "$3" > /dev/null && touch "$2"
}
# Run function (in background)
sleep_n_touch "$lifetime" "$tmp_name" $$ &
# #############################
# INSERT CODE TO CONTINUE ^^
sleep 3
# Get exit state of last executed command
# Might get placed elsewhere, if needed
state=$?
# #############################
if [[ -f "$tmp_name" ]]; then
# TIMEOUT WAS REACHED
rm -f "$tmp_name"
exit "$to_exit"
else
# TIMEOUT NOT REACHED
exit "$state"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment