我有一个带有循环的bash脚本,每次迭代都会调用一个硬计算例程。我将每次计算的结果用作下一个的输入。我需要make bash停止脚本读取,直到每个计算完成。
for i in $(cat calculation-list.txt)
do
./calculation
(other commands)
done
我知道sleep
程序,我曾经使用它,但现在计算时间差别很大。
感谢您提供任何帮助。
P.S> “./calculation”是另一个程序,并打开一个子进程。然后脚本立即传递到下一步,但我在计算中得到一个错误,因为最后一个还没有完成。
答案 0 :(得分:1)
如果您的计算守护程序将使用预先创建的空日志文件,则inotify-tools
程序包可能会起作用:
touch $logfile
inotifywait -qqe close $logfile & ipid=$!
./calculation
wait $ipid
(编辑:剥离一个流浪的分号)
如果它只关闭文件一次。
如果它正在进行打开/写入/关闭循环,也许您可以修改守护进程以围绕执行包装一些其他文件系统事件? `
#!/bin/sh
# Uglier, but handles logfile being closed multiple times before exit:
# Have the ./calculation start this shell script, perhaps by substituting
# this for the program it's starting
trap 'echo >closed-on-calculation-exit' 0 1 2 3 15
./real-calculation-daemon-program
答案 1 :(得分:0)
好吧,伙计们,我用不同的方法解决了我的问题。计算完成后,将创建一个日志文件。然后我用until
命令写了一个简单的sleep
循环。虽然这很难看,但它对我有用,而且还不够。
for i in $(cat calculation-list.txt)
do
(calculations routine)
until [[ -f $logfile ]]; do
sleep 60
done
(other commands)
done
答案 2 :(得分:-1)
易。通过一些awk
魔法获取进程ID(PID),然后使用wait
等待该PID结束。来自高级Bash脚本编制指南的are the details on wait
:
暂停脚本执行,直到所有在后台运行的作业都有 终止,或直到将作业号或进程ID指定为 选项终止。返回waited-for命令的退出状态。
您可以使用wait命令阻止脚本在a之前退出 后台工作完成执行(这将创建一个可怕的孤儿 处理)。
在代码中使用它应该像这样工作:
for i in $(cat calculation-list.txt)
do
./calculation >/dev/null 2>&1 & CALCULATION_PID=(`jobs -l | awk '{print $2}'`);
wait ${CALCULATION_PID}
(other commands)
done