1

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.

2
  • Yes? If you code it like that? Commented Apr 24, 2014 at 14:00
  • @JoachimPileborg How can I program it to restart itself? Commented Apr 24, 2014 at 14:01

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

The problem with your solution is that a process can't monitor if it is itself being killed.
I was thinking the stop and start would be inside initd script
Ok, so firing up a new process that runs a initd restart. That is an option, thank you.
1

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

Comments

0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.