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

2019-03-27 08:45发布

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.

3条回答
【Aperson】
2楼-- · 2019-03-27 09:06

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.

查看更多
Viruses.
3楼-- · 2019-03-27 09:06

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.

查看更多
Melony?
4楼-- · 2019-03-27 09:17

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

查看更多
登录 后发表回答