【发布时间】:2018-10-16 16:46:19
【问题描述】:
场景:
我有一个在嵌入式 linux 上运行的 shell 脚本。该脚本启动一个需要打开变量状态的应用程序。
代码:
所以我就这样做了
#!/bin/sh
start_my_app=false
wait_for_something=true
while $wait_for_something; do
wait_for_something=$(cat /some/path/file)
if [ "$wait_for_something" = "false" ]
then
echo Waiting...
elif [ "$wait_for_something" = "true" ]
then
echo The wait has ended
wait_for_something=false
start_my_app=true
else
fi
done
if [ "$start_my_app" = "true" ]
then
/usr/bin/MyApp
fi
#End of the script
/some/path/file 有一个值false,并在几秒钟内被不同组件中的另一个脚本转换为true。然后随着逻辑的发展,我脚本中的wait_for_something 变为true 并启动/usr/bin/MyApp。
问题和问题:
但我想以更好的方式做到这一点。
我不想在等待一段时间后无限期地等待/some/path/file 中的内容值true。
我想等待 /some/path/file 中的内容值设置为 true 仅 5 秒。如果/some/path/file 在 5 秒内不包含true,我想将start_my_app 设置为false。
如何在 linux 上的 shell 脚本中实现此功能?
PS:
我的整个脚本由另一个脚本在后台运行
【问题讨论】:
-
你在每次检查之间睡 2 秒。为什么不在 3 次后停止迭代,总共约 6 秒?
-
我取消了睡眠,但我想我可以等待经过的秒数到 6 我猜
-
你应该至少睡一小会儿。使用 100% CPU 5 秒没有意义。另一种方法是使用命名管道而不是常规文件,您可以等待超时。
-
啊。好的。那是一个好点,我应该取消睡眠。好的。我发现in this discussion 的另一件事是,有一种方法可以检查我等待了多少时间。