I want a way to write a daemon in a shell script, which runs another application in a loop, restarting it if it dies.
- When run using
./myscript.shfrom an SSH session, it shall launch a new instance of the daemon, except if the daemon is already running. - When the SSH session ends, the daemon shall persist.
- There shall be a parameter (
./myscript -stop) that kills any existing daemon.
(Notes on edit – The original question specified that nohup and similar tools may not be used. This artificial requirement was an “XY question”, and the accepted answer in fact uses all the tools the OP claimed were not possible to use.)
Based on clarifications in comments, what you actually want is a daemon process that keeps a child running, relaunching it whenever it exits. You want a way to type “./myscript.sh” in an ssh session and have the daemon started.
Run the script: it will launch the daemon process for you with nohup. The daemon process is a loop that watches for the child to exit, and relaunches it when it does.
To control the daemon, there’s a
-stopargument the script can take that will kill the daemon. Look at examples in your system’s init scripts for more complete examples with better error checking.