Question

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.

Was it helpful?

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.

OTHER TIPS

Break down the restart as two steps, stop and start. if your program takes time to stop, it should be handled in the stop function, I can't comment on specifics since I don't know your usecase, but I'd imagine monitoring the process to check if it's terminated will be a graceful way to stop

Do whatever shut-down/clean-up you need to do, then call this:

execl( argv[0], argv, reinterpret_cast< char* >( 0 ) );

Just like fork() and exec(), but skipping the fork. The exec will replace the current process with a new copy of itself. cf. http://linux.die.net/man/3/exec

Your init script should just kill your daemon and start it again. Don't try to restart your daemon FROM your daemon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top