Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 385
Thom Smith Avatar asked Dec 01 '11 06:12

Thom Smith


3 Answers

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.

like image 194
rosenfeld Avatar answered Nov 08 '22 21:11

rosenfeld


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

like image 5
tripleee Avatar answered Nov 08 '22 19:11

tripleee


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.

like image 1
Cougar Avatar answered Nov 08 '22 21:11

Cougar