Skip to content

Instantly share code, notes, and snippets.

@codeofnode
Created November 27, 2019 08:09
Show Gist options
  • Save codeofnode/fa2848e562b121ed101588edca41b436 to your computer and use it in GitHub Desktop.
Save codeofnode/fa2848e562b121ed101588edca41b436 to your computer and use it in GitHub Desktop.
timeout for child process with its exit code
#!/bin/sh
timeout() {
# Spawn a child process:
($1) & pid=$!
# in the background, sleep for x secs then kill that process
(sleep ${2:-'10'} && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
wait $pid && exit_code=$?
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?
if [ "$exit_code" == "0" ]; then exit $finished_gracefully; fi
exit 1
}
timeout "$@"
# Usage
# timeout "<your command>" [<number_of_seconds_for_timeout>=10]
# timeout "./my-shell-script.sh" 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment