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.
To create a daemon, you need a background process whose parent process is init. In the code above, _daemon creates a child process and then kills the parent process. In this case, your new process will be a subprocess of init and will continue to run in the background.
Starting daemons. Daemons can be started by JCL and also by the shell. Some daemons such as inetd can also be started by the shell. Interactive login shells, shell scripts run as background jobs from a login shell, and batch jobs using BPXBATCH to run the shell all can start daemons.
The SIGHUP (“hang-up”) signal is used to report that the user's terminal is disconnected, perhaps because a network or telephone connection was broken.
Depending on how cleanly your program is written, there are (at least) three ways to do that:
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With