I'm wondering if there is a better way to make a daemon that waits for something using only sh than:
#! /bin/sh
trap processUserSig SIGUSR1
processUserSig() {
echo "doing stuff"
}
while true; do
sleep 1000
done
In particular, I'm wondering if there's any way to get rid of the loop and still have the thing listen for the signals.
See Bash Service Manager project: https://github.com/reduardo7/bash-service-manager
Implementation example
Usage example
Use your system's daemon facility, such as start-stop-daemon.
Otherwise, yes, there has to be a loop somewhere.
If I had a
script.sh
and i wanted to execute it from bash and leave it running even when I want to close my bash session then I would combinenohup
and&
at the end.example:
nohup ./script.sh < inputFile.txt > ./logFile 2>&1 &
inputFile.txt
can be any file. If your file has no input then we usually use/dev/null
. So the command would be:nohup ./script.sh < /dev/null > ./logFile 2>&1 &
After that close your bash session,open another terminal and execute:
ps -aux | egrep "script.sh"
and you will see that your script is still running at the background. Of cource,if you want to stop it then execute the same command (ps) andkill -9 <PID-OF-YOUR-SCRIPT>
Just backgrounding your script (
./myscript &
) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so thatSIGHUP
does not kill it. You can take a shortcut to make a script appear to act like a daemon;will do the job. Or, to capture both stderr and stdout to a file:
However, there may be further important aspects that you need to consider. For example:
chdir("/")
(orcd /
inside your script), and fork so that the parent exits, and thus the original descriptor is closed.umask 0
. You may not want to depend on the umask of the caller of the daemon.For an example of a script that takes all of these aspects into account, see Mike S' answer.
Have a look at the daemon tool from the libslack package:
http://ingvar.blog.linpro.no/2009/05/18/todays-sysadmin-tip-using-libslack-daemon-to-daemonize-a-script/
On Mac OS X use a launchd script for shell daemon.