1

Suppose I have bash-script with following code:

function test() {
  some_code
  ...
  make
  some_code
}

test
some_other_code

test() could contain any code that might run unreasonably long.

I was trying to use something like:

function test() {
  cd $WORK_FOLDER
  make
}

run_timeout()
{
local timeout=$1
$2 &
local pid=$!
while ps $pid >/dev/null && [ $timeout -ne 0 ]; do
  sleep 1
  let timeout--  
done  
kill -9 $pid 2>/dev/null && echo "Process $pid killed because executed too long"
}

run_timeout 15 "test"
run_timeout 5 "test"

But make was still running after the estimated time.

Any suggestion how to solve this problem?

Is there any technique that prevents a bash script from hanging?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
art_tykh
  • 169
  • 1
  • 17
  • 4
    It's probably not a good idea to use `test` as a function command since it's a built in *nix command – nullByteMe Jun 14 '13 at 13:38
  • http://stackoverflow.com/questions/392022/best-way-to-kill-all-child-processes – ctn Jun 14 '13 at 13:38
  • 2
    You probably want to see http://stackoverflow.com/questions/687948/timeout-a-command-in-bash-without-unnecessary-delay – devnull Jun 14 '13 at 13:51
  • 2
    Welcome to Stack Overflow. Please read the [FAQ] soon. Note that you are expected to use full words rather than 'SMS-ese' abbreviations (so 'something', not 'smth'). Generally, it is not a good idea to jump straight to `kill -9`; use `kill -15` (aka `TERM`), and `kill -1` (aka HUP) before resorting to `kill -9` (aka KILL). – Jonathan Leffler Jun 14 '13 at 14:13

1 Answers1

0

I guess the $2 & is where you run the long function right? I had the same problem and some time, depending on what is in the function you will have multiple process ... I don t know if my solution is the best way to do it, but it worked for me.

change :

$2 &

for :

awk '{system($2)}' &

this way, pid =$! will give you the awk pid and by killing the awk, you kill the whole process thing.

Franko
  • 131
  • 1
  • 10
  • I think this is a prime example of why software packages keep getting slower and slower, requiring processors to get faster and faster, and systems needing more and more memory... – twalberg Jun 14 '13 at 14:30