Programming method for Linux daemon
The daemon is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some events. The daemon is a very useful process. Most of Linux is implemented with daemon. For example, the Internet server inetd, web server httpd, etc. At the same time, the daemon completes many system tasks. For example, the job planning process crred, print process LPD, etc.
The programming of the daemon is not complicated, complex is that the implementation mechanism of various versions of UNIX is not the same, causing programming rules in different UNIX environments and inconsistent. This requires readers to pay attention to the rules on certain books (especially BSD4.3 and low version of System v) to Linux will have errors. The program key points of the daemon under Linux will be fully introduced below and give a detailed instance.
One. Daemon and its characteristics
The most important feature of daemon is the background run. At this point, the resident memory program TSR under DOS is similar. Second, the daemon must be separated from the environment before its run. These environments include unsturned file descriptors, control terminals, sessions, and process groups, working directories, and file creation masks. These environments are usually the daemon inherited from the execution of its parent process (especially shell). Finally, the launch method of the daemon has its own special. It can start from the startup script /etc/rc.d when the Linux system is started, can be started by the job planning process crones, and can also be performed by the user terminal (usually the shell).
In summary, the daemon is basically no different from the normal process outside of these specialities. Therefore, the writing daemon is actually the transformation of a normal process in accordance with the characteristics of the above daemon as a daemon. If the reader has more in-depth understanding of the process, it is easier to understand and program.
two. Programming point for daemon
As mentioned earlier, the programming rules of daemon in different UNIX environments are inconsistent. Fortunately, the programming principle of the daemon is actually the same, and the difference is that the specific implementation details are different. This principle is to meet the characteristics of the daemon. At the same time, Linux is SVR4 based on SYETEM V and follows the POSIX standard, which is more convenient than BSD4. The programming points are as follows;
1. Run in the background.
To avoid suspend control terminals, put daemon in the background. The method is to call the Fork in the process to terminate the parent process, let Daemon execute in the sub-process.
IF (PID = for ())
EXIT (0); // is the parent process, ending the parent process, the child process continues
2. Dive from the control terminal, login session and process group
It is necessary to introduce the relationship between the process and the control terminal in Linux and the control terminal, login session, and process group: The process belongs to a process group, the process group number (GID) is the process number (PID) of the process team. The login session can contain multiple processes groups. These process groups share a control terminal. This control terminal is usually a login terminal that creates a process.
Control terminals, login sessions, and process groups are usually inherited from the parent process. Our goal is to get rid of them, so that it is not affected by them. The method is based on the 1st point, calling setsid () to make the process a session group leader:
setsid ();
Description: When the process is when the session group is long, the setsid () call failed. But the first point has assured that the process is not a session team leader. After the setsid () call is successful, the process becomes a new session group leader and a new process team leader and detached from the original login session and process group. Due to the exclusiveity of the control terminal, the process is simultaneously detached from the control terminal.
3. Prohibit Process Re-opening the control terminal
The process now has become a long-term session leader. But it can reapply, open a control terminal. You can prohibit process re-opening control terminals by making the process no longer a session group length: IF (pid = fork ())
EXIT (0); // End the first child process, the second child process continues (the second child process is no longer a session leader)
4. Close the open file descriptor
The process inherits the open file descriptor from the parent process created. If it is not closed, the system resources will be wasted, resulting in the file system in which the process is located cannot be removed and causing an unpredictable error. Close them as follows:
For (i = 0; i close the open file descriptor close (i);>
5. Change the current work directory
When the process activity, the file system in which its working directory cannot be removed. It is generally necessary to change the work directory to the root directory. For processes that require dump cores, write traffic logs to change the work directory to specific directorys such as / tmpchdir ("/")
6. Reset file creation mask
The process inherits the file creation mask from the created parent process. It may modify the access position of the file created by the daemon. To prevent this, create a mask clearance: umask (0);
7. Handle SigchLD signal
It is not necessary to handle SIGCHLD signals. However, for some processes, especially server processes are often generated when requested. If the parent process does not wait for the child to end, the child process will become a zombie process (Zombie) to take up system resources. If the parent process is waiting for the sub-process, it will increase the burden on the parent process, affect the concurrency performance of the server process. The operation of the SIGCHLD signal can be simply set to SIG_IGN under Linux.
Signal (SIGCHLD, SIG_IGN);
In this way, the kernel does not generate a zombie process at the end of the child. This is different from BSD4, and BSD4 must be explicitly waiting for the sub-process to release the zombie process.
three. Guarding process instance
The daemon example includes two parts: main program Test.c and initializer init.c. The main program reports the running status of the log test.log in the / TMP directory every other minute. The init_daemon function in the initializer is responsible for generating a daemon. Readers can use the init_daemon function to generate their own daemon.
1. Init.c list
#include
#include
#include
#include
#include
Void Init_Daemon (Void)
{
int PI;
INT I;
IF (PID = for ())
EXIT (0); // is a parent process, ending the parent process
ELSE IF (PID <0)
EXIT (1); // Fork failed, exit
/ / Is the first child process, the background continues to execute
Setsid (); // The first child process becomes a new session leader and the process team leader
/ / Separate with the control terminal
IF (PID = for ())
EXIT (0); // is the first child process, end the first child process
ELSE IF (PID <0)
EXIT (1); // Fork failed, exit
// is the second child process, continue
// The second child is no longer a conversation team
For (i = 0; i Close (i); Chdir ("/ tmp"); // Change the work directory to / TMP umask (0); // Reset file creation mask Return; } 2. Test.c list #include #include Void init_daemon (void); // daemon initialization function main () { File * fp; Time_t t; INIT_DAEMON (); // Initialization is daemon While (1) // Reports to Test.log every other minute { Sleep (60); // Sleep one minute IF ((fp = fopen, "a"))> = 0) { T = Time (0); FPRINTF (FP, "IM Here AT% S / N", Asctime (LocalTime (& T)); Fclose (fp); } } } The above program is compiled by redhat Linux6.0. Proceed as follows: Compilation: gcc -g -o test init.c test.c Execute: ./ Test View processes: ps -ef The various characteristics of the TEST daemon can be found in the output of the TEST daemon meet the above requirements.