我正在编写一个bash脚本,其中必须执行3个命令。
1
必须每10秒在后台运行一次2
并且3
必须在后台运行一次。1
必须在命令2
和3
执行之前至少成功执行一次,因为它会生成/更新最后2个文件才能正常运行所需的文件。但是,我不知道如何使命令1
在这些条件下运行...我不能将awhile(1)
与asleep 10
或类似的东西一起使用,因为那样我将永远无法到达命令2
and 3
。
我缺少什么bash脚本概念?线程,也许吗?
编辑:命令1
可以像在.txt文件中递增整数一样简单,此文件将在command2
和中使用3
。
我缺少什么bash脚本概念?线程,也许吗?
作业控制。您可以在后台启动进程,并通过了解进程ID和退出状态对其进行相当精细的控制。
要获取后台命令的PID,请使用$!
变量。
要获取后台命令的退出状态,请使用wait()
并提供其PID。请注意,wait()
如果命令尚未退出,则对的调用将阻塞。如果这种阻塞是有问题的(可能是您的情况),则可以ps
在调用之前使用(或其他方法)执行检查,wait()
以查看是否准备好收获进程,通常是在存在看门狗或其他某种事件的循环中进行限制任务执行时间的方法。
考虑以下基于循环的样板:
complete=0
cycles=0
# Task 1
sleep 200 &
pid=$!
while [[ complete -eq 0 ]]; then
ps -o pid= -p $pid > /dev/null
if [[ $? -ne 0 ]]; then
# Signal complete to logic below
complete=1
break;
fi
# Perform some timeout / cycle check to give up on this task
cycles=$((cycles + 1))
if [[ $cycles -gt 100 ]]; then # whatever, this is just a simple watchdog example
break;
fi
# Optional sleep
sleep 1
done
if [[ $complete -eq 1 ]]; then
# Process the command's exit status
wait $pid
if [[ $? -ne 0 ]]; then
: # handle command failed perhaps
else
: # do other things, assuming exit of 0 is a good thing
fi
else
# Process a command watchdog failure
kill -9 $pid # come what may
fi
对于更复杂的作业控制,您可以将命令检查和周期管理移至bash函数中,并清理大量代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句