Search code examples
c++linuxdaemonstart-stop-daemon

Restarting a linux daemon


I have Linux daemon that I have written in C++ that should restart itself when given a "restart"-command from a user over the network through its console. Is this possible? I use a /etc/init.d script. How can I program it to restart itself? Should I launch a new process with a very long delay (one minute) that then fires the shell script again ? Problem is that the daemon may take a very long time to close down and it could take even more than a minute in a worst-case scenario.


Solution

  • There are basically three ways for an application to restart itself:

    1. When the application is told to restart, it does proper clean-up, releases all resources it has allocated, and then re-initializes like it was started from scratch.

    2. Fork a new process, where the new child process execs itself and the parent process exits normally.

    3. The daemon is actually just a wrapper application, much like an init-script. It forks a new process which runs the actual application, while the parent process just waits for it to exit. If the child process (and the real application) returns with a special exit-code, it means that it should be restarted so the forks/execs all over again.

    Note that points 2 and 3 are basically the same.