LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Restarting a server daemon (http://www.linuxquestions.org/questions/programming-9/restarting-a-server-daemon-752457/)

wtruong 09-03-2009 12:48 PM

Restarting a server daemon
 
Hello all,

I'm writing a program which acts like a server daemon. I want to know if it's possible to make the program restart itself when I receive a particular type of message from a client that I am listening to.

Thanks

William

raconteur 09-03-2009 01:23 PM

I suggest making your daemon respond appropriately to SIGHUP. How you (or the client) generate the signal is up to you and there are myriad methods.

wtruong 09-03-2009 01:28 PM

What do I do in the function that I call from catching SIGHUP? I want to restart the main block after properly closing anything that has been opened by my server.

raconteur 09-03-2009 03:50 PM

Being very general, I'd say clean up in the child process and have it exit, then fork again. One way to do that is to set up a specific return value in the child and watch for that in the parent. If the child exits with that value, fork another one.

chrism01 09-04-2009 12:39 AM

If you want a clean full restart, see exec http://linux.die.net/man/3/exec

wtruong 09-04-2009 12:53 PM

wow that's a powerful system call. Thanks

wtruong 09-04-2009 04:12 PM

However, I believe that forking is still more graceful, since I can know that the stack rolled back up when it returns, whereas when you do an exec you won't know how much junk you accumulate on the stack.

ta0kira 09-04-2009 09:22 PM

You might just run a script like this as your daemon:
Code:

#!/bin/bash


function daemon_loop()
{
  false #<-- replace with daemon stuff (perhaps exec daemon $*)
}


while ( daemon_loop $* ); do
  sleep 1
done

This will restart the daemon when it exits unless it exits with an error. You'd need to make the actual daemon exit without error when given e.g. the SIGHUP signal to indicate that it should be restarted.
Kevin Barry

PS Another option is to design it to work with xinetd, which won't actually start it until a connection is made; there will be one fork per connection.


All times are GMT -5. The time now is 02:31 AM.