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.
-
Yes? If you code it like that? – Some programmer dude Apr 24 '14 at 14:00
-
@JoachimPileborg How can I program it to restart itself? – Apr 24 '14 at 14:01
4 Answers
There are basically three ways for an application to restart itself:
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.
Fork a new process, where the new child process execs itself and the parent process exits normally.
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.

- 400,186
- 35
- 402
- 621
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

- 51
- 10
-
The problem with your solution is that a process can't monitor if it is itself being killed. – Apr 24 '14 at 14:19
-
-
Ok, so firing up a new process that runs a `initd` restart. That is an option, thank you. – Apr 25 '14 at 07:46
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

- 8,757
- 2
- 32
- 36
Your init script should just kill your daemon and start it again. Don't try to restart your daemon FROM your daemon.

- 800
- 4
- 7
-
The daemon may - through its console - get a command over the network to restart, so this is not an option in my scenario. Each daemon is part of a distributed system. There is no one logged into the Linux box that runs the daemon, the "restart"-command comes remotely. – Apr 24 '14 at 14:06