[英]Prevent bash script from hanging
Suppose I have bash-script with following code: 假设我有以下代码的bash脚本:
function test() {
some_code
...
make
some_code
}
test
some_other_code
test() could contain any code that might run unreasonably long. test()可以包含任何可能运行不合理时间的代码。
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. 但是make在估计的时间后仍在运行。
Any suggestion how to solve this problem? 有什么建议如何解决这个问题?
Is there any technique that prevents a bash script from hanging? 有没有什么技术可以防止bash脚本挂起?
I guess the $2 & is where you run the long function right? 我猜$ 2&是您在运行long函数的地方吗? 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 =$! 这样,pid = $! will give you the awk pid and by killing the awk, you kill the whole process thing.
将为您提供awk pid,并通过杀死awk来杀死整个过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.