Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart C daemon program in Linux after receiving SIGHUP signal

Tags:

c

linux

daemon

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.

like image 955
user356197 Avatar asked Jun 02 '10 07:06

user356197


People also ask

How do I start the daemon process in Linux?

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.

How do you start a daemon?

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.

What is Sighup signal?

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.


1 Answers

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).

like image 168
Jonathan Leffler Avatar answered Oct 09 '22 22:10

Jonathan Leffler