等待多个bash函数finsih或在超时时退出它们



In有一个函数,我在循环中并行调用它:

#!/bin/bash
my_func()
{
until [[ $entity status is OK ]]; do
sleep 5
echo "count=$count"
if (( timeout_flag == 1 )); then
break
fi
done
}
_arr=(e1 e2 e3)
count=0
timeout=60
timeout_flag=0
for entity in "${_arr[@]}"; do
my_func "${entity}" &
done
while [[ "${count}" -lt "${timeout}" ]]; do
sleep 5
count=count+5
done
timeout_flag=1
echo "Timeout reached"
sleep 1

我希望所有功能定期检查,直到实体的状态正常,然后等待所有正常状态,或者在超时时停止所有(剩余(功能?先到先得。以上似乎不起作用,我需要手动删除它。

  • 为什么我在最后得到"Timeout reached"的响应,而脚本没有等待函数完成?

  • 为什么my_func和中的count=0没有增加?

如果您想在60秒后使每个函数超时,可以使用timeout命令;它正是为了这个目的而制造的:

#!/bin/bash                                                                                                                                                                                   
my_func() {
to_sleep=$1
stdbuf -oL echo "Request to sleep at least $to_sleep s"
slept=0
while [[ $slept -lt $to_sleep ]]; do
sleep 1
slept=$((slept + 1))
done
echo "Successfully slept $slept s ($to_sleep s requested)"
}
export -f my_func
_arr=(1 3 5)
maxtime=4s
for entity in "${_arr[@]}"; do
stdbuf -oL echo "Launching with $entity s"
timeout $maxtime bash -c "my_func $entity" &
done

输出为

Launching with 1 s
Launching with 3 s
Launching with 5 s
Request to sleep at least 1 s
Request to sleep at least 3 s
Request to sleep at least 5 s
Successfully slept 1 s (1 s requested)
Successfully slept 3 s (3 s requested)

请注意,"5s"案例没有成功。

注:

  • stdbuf -oL用于直接刷新回波输出
  • 添加了export -f my_functimeout $maxtime bash -c,使您的函数在timeout启动的新shell中可见,遵循此答案

最新更新