Bash – How should I idle until I get a signal?

十年热恋 提交于 2019-12-21 03:59:16

问题


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?

#!/bin/bash

cd "`dirname "$0"`"

trap "./serverctl stop" TERM
./serverctl start

# wait to receive TERM signal.

回答1:


A plain wait would be significantly less resource-intensive than a spin lock, even with a sleep in it.




回答2:


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:

#!/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

Another alternative to "sleep infinity" (it seems busybox doesn't support it for example) could be "tail -fn0 $0" for example.




回答3:


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.

To do this thing by design you have to install your serverctl script as rc script and let init (start and) stop that. Here I described how to set up server process that is not originally designed to work as server.



来源:https://stackoverflow.com/questions/8337472/bash-how-should-i-idle-until-i-get-a-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!