On 07/27/2010 12:05 PM, Andreas Schwab wrote: > If you want to kill the whole background job you need to enable job > control (set -m) and call kill with the job specifier instead (kill %2 > in this case). > >> How can the wait call affect a job it's not supposed to wait for? > > It's a simple race. You may not give the subshell enough time to > acutally execute the sleep command.
Hi Andreas, thanks a lot. I suspected it might be something simple like that. "set -m" solved the problem for me. What I was going for was a script which executes another command with a timeout. This is what I now came up with: ------------ #!/bin/bash if [[ $# -lt 2 ]]; then echo "Usage: $(basename $0) timeout_in_seconds commandline..." echo "Runs the command and sends SIGTERM to the child after the specified timeout." exit 0 fi # Enable job control. set -mb TIMEOUT="$1" shift # Use SIGUSR1 to interrupt the wait call. trap ':' USR1 # Run the desired command. "$@" & # Suppress any output from now on. exec &>/dev/null # Run the watchdog. { sleep $TIMEOUT ; kill -USR1 $$; } & # Give the command a chance to complete. wait %1 EXIT_STATUS=$? # Send SIGTERM to the watchdog and the command. If a job is not # running, the kill has no effect. kill %2 kill %1 exit $EXIT_STATUS ------------ It works in all my test cases. Because I'm still learning to write bash scripts, I'd be very interested to know if there are any obvious blunders in the way I did it (or more subtle mistakes). Also, is there a more elegant way to achieve the same effect? I thought running a process with a time limit would not be such an unlikely thing to do. Christoph