Programming implementation of the Linux daemon (GO)

Source: Internet
Author: User

http://blog.csdn.net/zg_hover/article/details/2553321

http://blog.csdn.net/kongdefei5000/article/details/8808147

A daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons are a very useful process. Most Linux servers are implemented with daemons. For example, the Internet server Inetd,web server httpd and so on. At the same time, the daemon completes many system tasks. For example, the job planning process Crond, the printing process lpd and so on.
The daemon programming itself is not complex, the complexity of the various versions of UNIX implementation mechanism is not the same, resulting in different UNIX environment daemon programming rules are not consistent. This requires the reader's attention that copying some of the rules of the book (especially BSD4.3 and the lower version of System V) to Linux will be wrong. Below is a full description of the programming essentials of the Linux daemon and gives a detailed example.
A Daemon and its characteristics
The most important feature of the daemon is running in the background. At this point, the resident memory program in DOS is similar to the TSR. Second, the daemon must be isolated from the environment before it runs. These environments include file descriptors that are not closed, control terminals, session and process groups, working directories, and file creation masks. These environments are typically inherited by daemons from the parent process that executes it, especially the shell. Finally, the way the daemon is launched has its special place. It can be started from the startup script/ETC/RC.D when the Linux system starts, can be started by the job planning process Crond, and can be performed by the user terminal (usually the shell).
In short, despite these peculiarities, daemons are basically no different from ordinary processes. Therefore, the process of writing a daemon is actually transforming a normal process into a daemon based on the nature of the daemon described above. It is easier to understand and program if the reader has a deeper understanding of the process.
Two Programming Essentials for Daemons
As mentioned earlier, the programming rules for daemons in different UNIX environments are not consistent. Fortunately, the Daemon programming principle is the same, the difference is that the specific implementation details are different. The principle is to satisfy the nature of the daemon. At the same time, Linux is based on Syetem v SVR4 and follows the POSIX standard, which is more convenient than BSD4. Programming essentials are as follows;
1. Run in the background.
To avoid suspending the control terminal, put the daemon into the background. The method is to call fork in the process to terminate the parent process, allowing Daemon to execute in the background in the child process.
if (Pid=fork ())
Exit (0);//is the parent process that ends the parent process, and the child process continues
2. Out of control terminal, logon session and process group
It is necessary to introduce the relationship between the process and the control terminal in Linux, the logon session and the process group: the process belongs to a process group, and the process group number (GID) is the process number (PID) of the process leader. A logon session can contain multiple process groups. These process groups share a control terminal. This control terminal is usually the login terminal of the creation process.
Control terminals, logon sessions and process groups are usually inherited from the parent process. Our aim is to get rid of them so that they are not affected by them. The method is based on the 1th, call Setsid () to make the process a conversation leader:
Setsid ();
Description: The Setsid () call failed when the process was the session leader. But the 1th has ensured that the process is not a conversation leader. After the Setsid () call succeeds, the process becomes the new session leader and the new process leader, and is detached from the original logon session and process group. Due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal at the same time.
3. Disable process re-opening control terminal
Now, the process has become a session leader without terminal. But it can be re-applied to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer a session leader:

if (Pid=fork ())
Exit (0);//End first child process, second child process continue (second child process is no longer a conversation leader)
4. Close the Open file descriptor
The process inherits the open file descriptor from the parent process that created it. Without shutting down, system resources will be wasted, causing the file system where the process is located to fail to unload and cause unexpected errors. Close them as follows:
For (i=0;i Close Open file descriptor Close (i);>
5. Change the current working directory
The file system in which the working directory resides cannot be unloaded while the process is active. It is generally necessary to change the working directory to the root directory. For processes that require dump cores, the process that writes the log changes the working directory to a specific directory such as/tmpchdir ("/")
6. Resetting the file creation mask
The process inherits the file creation mask from the parent process that created it. It may modify the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared: umask (0);
7. Handling SIGCHLD Signals
Processing SIGCHLD signals is not a must. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. If the parent process waits for the child process to end, it increases the burden on the parent process and affects the concurrency performance of the server process. The operation of the SIGCHLD signal can be easily set to Sig_ign under Linux.
Signal (sigchld,sig_ign);
This way, the kernel does not spawn a zombie process at the end of the child process. Unlike BSD4, the BSD4 must explicitly wait for the child process to end before releasing the zombie process.
Three Daemon Process Instance
The daemon instance consists of two parts: the main program TEST.C and the initialization program INIT.C. The main program reports the running state to the log test.log in the/tmp directory every minute. The Init_daemon function in the initialization program is responsible for generating the daemon. Readers can use the Init_daemon function to generate their own daemons.
1. INIT.C List

#include < unistd.h >#include< signal.h >#include< sys/param.h >#include< Sys/types.h >#include< sys/stat.h >voidInit_daemon (void) { intpid;inti;if(pid=Fork ()) Exit (0);//is the parent process that ends the parent processElse if(pid<0) Exit (1);//Fork failed, exit//is the first child process, the background continues to executeSetsid ();//the first child process becomes the new conversation leader and process leader//and separated from the control terminalif(pid=Fork ()) Exit (0);//is the first child process, ending the first child processElse if(pid<0) Exit (1);//Fork failed, exit//is the second child process, continue//The second child process is no longer a conversation leader for(i=0;i< nofile;++i)//Close Open File descriptorClose (i); ChDir ("/ tmp");//change the working directory to/TMPUmask0);//resetting file creation masksreturn; } 

2. TEST.C List

#include < stdio.h >#include< time.h >voidInit_daemon (void);//Daemon Initialization functionMain () {FILE*FP; time_t t; Init_daemon ();//Initialize to daemon while(1)//report running status to Test.log every minute{sleep ( -);//one minute of sleepif((Fp=fopen ("Test.log","a")) >=0) {T=time (0); fprintf (FP,"Im here at%s/n", Asctime (LocalTime (&T))) ; Fclose (FP); } } } 

The above program is compiled and passed under Redhat Linux6.0. The steps are as follows:
Compilation: Gcc-g-O test init.c test.c
Execution:./test
View process: Ps-ef
The various features of the test daemon can be found from the output to meet the requirements above.

Description: There is a library function in the system call library that can directly make a process a daemon.
#include <unistd.h>
int daemon (int nochdir, int noclose);

Example:

/** Function: Create a daemon to monitor all running processes of the system*/#include<unistd.h>#include<signal.h>#include<sys/types.h>#include<sys/stat.h>#include<stdio.h>#include<stdlib.h>#include<sys/resource.h>#include<unistd.h>intMain () {FILE*FP; FILE*FStream; Signal (SIGCHLD, sig_ign); //Ignore child process end signals to prevent zombie processes from appearingDaemon0,0);//initializes the daemon, which is the creation of a daemon process     while(1)    {            /*PID Process ID, User: Process open users, Comm: Process name, Lstart: Process start time, ETime: Process duration*/FStream=popen ("Ps-eo pid,user,comm,lstart,etime>test.txt","R"); //write error report If execution command fails        if(fstream==NULL) {            //Write error (failed when using errno) when opening or creating Error.log success            if(fp = fopen ("Error.log","A +")) !=NULL) {fprintf (FP),"%s\n","failed to execute command");            Fclose (FP); }            ElseExit (1);//Write error failed, terminate program eject and close all processes        }        ElsePclose (fstream);//Turn off Popen open I/O streamSleep -);//set to 5 minutes get a system process condition    }    return 0;}

Programming implementation of the Linux daemon (go)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.