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?

4

1 回答 1

0

我猜 $2 & 是你运行 long 函数的地方吗?我有同样的问题,有一段时间,根据函数中的内容,你将有多个进程......我不知道我的解决方案是否是最好的方法,但它对我有用。

改变 :

$2 &

为了 :

awk '{system($2)}' &

这样,pid =$!会给你 awk pid,通过杀死 awk,你会杀死整个过程。

于 2013-06-14T14:24:55.050 回答