Bash - 在收到信号之前我应该如何空闲?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8337472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash – How should I idle until I get a signal?
提问by Thom Smith
I have a script for launchd to run that starts a server, then tells it to exit gracefully when launchd kills it off (which should be at shutdown). My question: what is the appropriate, idiomatic way to tell the script to idle until it gets the signal? Should I just use a while-true-sleep-1 loop, or is there a better way to do this?
我有一个用于启动服务器的启动脚本,然后在启动服务器时告诉它正常退出(应该在关闭时)。我的问题:告诉脚本空闲直到它得到信号的合适的惯用方法是什么?我应该只使用 while-true-sleep-1 循环,还是有更好的方法来做到这一点?
#!/bin/bash
cd "`dirname "#!/bin/bash
sleep infinity & PID=$!
trap "kill $PID" INT TERM
echo starting
# commands to start your services go here
wait
# commands to shutdown your services go here
echo exited
"`"
trap "./serverctl stop" TERM
./serverctl start
# wait to receive TERM signal.
采纳答案by tripleee
A plain waitwould be significantly less resource-intensive than a spin lock, even with a sleep in it.
一个平原wait比自旋锁占用的资源要少得多,即使它有一个睡眠。
回答by rosenfeld
You can simply use "sleep infinity". If you want to perform more actions on shutdown and don't want to create a function for that, an alternative could be:
您可以简单地使用“睡眠无限”。如果您想在关机时执行更多操作并且不想为此创建函数,则替代方法可能是:
##代码##Another alternative to "sleep infinity" (it seems busybox doesn't support it for example) could be "tail -fn0 $0" for example.
例如,“sleep infinity”的另一种选择(例如,busybox 似乎不支持它)可能是“tail -fn0 $0”。
回答by Cougar
Why would you like to keep your script running? Is there any reason? If you don't do anything later after signal then I do not see a reason for that.
为什么要保持脚本运行?有什么理由吗?如果你在发出信号后没有做任何事情,那么我看不出有什么原因。
When you get TERM from shutdown then your serverctl and server executable (if there is any) also gets TERM at the same time.
当您从关闭中获得 TERM 时,您的 serverctl 和服务器可执行文件(如果有)也会同时获得 TERM。
To do this thing by design you have to install your serverctl script as rc script and let init (start and) stop that. HereI described how to set up server process that is not originally designed to work as server.
要按设计执行此操作,您必须将 serverctl 脚本安装为 rc 脚本并让 init(启动和)停止它。在这里,我描述了如何设置最初不是用作服务器的服务器进程。

