bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Strange behavior with job control


From: Christoph Dittmann
Subject: Re: Strange behavior with job control
Date: Tue, 27 Jul 2010 13:44:26 +0200
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.11) Gecko/20100713 Thunderbird/3.0.6

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]