tags:

views:

295

answers:

3

Hello

Can anybody please post some example code on how I can reread a configuration file and restart my daemon after the daemon receives a SIGHUP signal. The daemon is a user space program written in C on Linux and is not started by inetd.

+1  A: 

Depending on how cleanly your program is written, there are (at least) three ways to do that:

  1. On receipt of the signal, return to the start of the program, before the initialization phase (possibly - but not necessarily - via a setjmp()/longjmp() or sigsetjmp()/siglongjmp() pair), thus resetting and rereading the configuration file.

  2. On receipt of the signal, have the signal handler exec the original program again. This has the merit of losing all the state and resetting all globals and static variables back to their original state. It has the demerit of losing all previous state.

  3. The third option is less brutal, perhaps; it would note that the signal has been received and at the next convenient point in the main processing loop, would go back and reread the configuration file.

What works depends in part on what your daemon has to do. If it spends time in a conversation with its clients, you may not want to use either of the options 1 or 2 - you would prefer to use option 3. If you are doing one-shot answers to simple questions, the brutal approaches may be effective (and are probably simpler to program). Note that option 1 requires careful handling of the WIP (work in progress) and things such as open files - if you are not careful, you will lose track of resources, and the daemon will fail (out of memory, out of file descriptors - most likely one of these two).

Jonathan Leffler
A: 

Depends how you structure it; if you handle multiple connections in a single thread / process, then you should probably somehow notify them to quit (if you can; depends on the protocol) before reloading the config (or exec itself).

If the protocol allows you to say "go away and come back later", then clearly doing that is a good win. If the clients need to remain connected, you could apply the config changes to already-connected clients, if it's a single-process-single-thread daemon, if that makes sense.

If it's multi process, things get more complex. You'd have to notify the processes about the new config, or ensure that they continue with the old config, or that they can pick the new config up when their client quits.

If it's multi thread, the threads would need to safely be able to read the new config in the middle of whatever they happened to be doing, which might need locking, or you could allocate memory for a new config structure and do a switch-over somehow,

MarkR