Linux programming-daemon Programming

Source: Internet
Author: User
Linux programming-daemon is a special process running in the background. It is independent of the control terminal and periodically executes a task or waits to process some events. Daemon is a very useful process. Most Linux servers are implemented using daemon. For example, the Internet server inetd and the Web Server httpd. At the same time, the daemon completes many system tasks. For example, job planning process crond and printing process LPD. The programming of daemon is not complex. The complicated problem is that different versions of UNIX have different implementation mechanisms, resulting in inconsistent programming rules of daemon in different UNIX environments. It should be noted that copying the rules in some books (especially bsd4.3 and earlier versions of System V) will cause errors to Linux. Next we will talk about the daemon programming with some documents from our predecessors and examples .. Basic concept: process. Each process has a parent process. When the child process is terminated, the parent process will be notified and can exit the child process .. Process Group. each process also belongs to a process group. each process master has a process group number, which is equal to the PID Number of the process group leader. A process can only set the process group ID for itself or its sub-processes. session Period. A session is a set of one or more Process Groups. The. setsid () function can establish a dialogue period. If the process that calls setsid is not the leader of a process group, this function creates a new session period. (1) The process becomes the first process in the dialog period (2) the process becomes the leader process of a new process group. (3) The process has no control terminal. If the process has a control terminal before calling setsid, the contact with the terminal is removed. If the process is the leader of a process group, this function returns an error. (4) To ensure this, we first call fork () and then exit (). At this time, only the child process is running and the child process inherits the ID of the parent process group, however, the process PID is newly allocated, so it cannot be the PID of the Process Group of the new session. This is ensured. If (pid = fork ()> 0) // parent exit (0); else if (pid = 0) {// Th1 child setsid (); // TH1 is the session leader if (Fork () = 0) {// 2's will not be the session leader (become an orphan Process Group )...}} i. daemon and its features (1) the most important feature of daemon is that it runs in the background. At this point, the TSR of the resident memory program under DOS is similar. (2) The Daemon must be isolated from the environment before running. These environments include unclosed file descriptors, control terminals, sessions and process groups, working directories, and file creation masks. These environments are generally inherited by the daemon from the parent process (especially the shell) that executes the daemon. (3) At last, the daemon startup method has its own special features. It can be started from the startup script/etc/rc. d when the Linux system is started. It can be started by the job planning process crond and executed by the user terminal (usually shell. In short, apart from these special features, the daemon process is basically no different from the common process. Therefore, writing a daemon actually transforms a common process into a daemon according to the features of the preceding daemon. Ii. Main Points of daemon programming (from ueap) As mentioned earlier, the programming rules of daemon in different UNIX environments are inconsistent. Fortunately, the programming principles of the daemon process are the same. The difference is that the specific implementation details are different. This principle is to satisfy the characteristics of the daemon process. At the same time, Linux is a svr4 Based on syetem V and complies with the POSIX standard, which is easier to implement than bsd4. The main points of programming are as follows; 1. running in the background. To avoid pending the control terminal, place the daemon in the background for execution. The method is to call fork in the process to terminate the parent process and run daemon in the background of the child process. If (pid = fork () Exit (0); // It is the parent process, ends the parent process, and the child process continues 2. from the control terminal, the logon session and process group process belong to a process group. The process group number (GID) is the process ID (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 that creates a process. Control terminal, logon sessions and process groups are generally inherited from the parent process. Our goal is to get rid of them so that they are not affected. The method is to call setsid () on the basis of to make the process become the session leader: setsid (); Description: setsid () fails to be called when the process is the session leader. However, the first point is that the process is not the session leader. After the setsid () call is successful, the process becomes a new session leader and a new process leader, and is detached from the original logon session and process group. Because the session process is dedicated to the control terminal, the process is separated from the control terminal at the same time. 3. Prohibit the process from re-opening the control terminal. Now, the process has become the no-end session leader. But it can re-apply to open a control terminal. You can prevent the process from re-opening the control terminal by making the process no longer the session leader: If (pid = fork () Exit (0); // end the first sub-process, the second sub-process continues (the second sub-process is no longer the session leader) 4. the closed file descriptor process inherits the opened file descriptor from the parent process that created it. If you do not close it, system resources will be wasted, and the file system where the process is located will not be able to be detached and unexpected errors will occur. Close them as follows: for (I = 0; I close the opened file descriptor close (I);> 5. when a process activity in the current working directory is changed, the file system in which the working directory is located cannot be detached. Generally, you need to change the working directory to the root directory. For processes that need to dump the core, write the running log to change the working directory to a specific directory such as/tmpchdir ("/") 6. the process of resetting the file creation mask 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, create a mask to clear the file: umask (0); 7. It is not necessary to process the sigchld signal. However, some processes, especially server processes, usually generate sub-processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process will become a zombie process, occupying system resources. If the parent process waits for the child process to end, it will increase the burden on the parent process and affect the concurrent performance of the server process. In Linux, you can set the sigchld signal operation to sig_ign. Signal (sigchld, sig_ign); in this way, the kernel will not generate botnets when the child process ends. This is different from bsd4. In bsd4, you must explicitly wait for the child process to end before releasing the zombie process. 3. The Daemon instance consists of the main program test. C and the initialization program init. C. The main program reports the running status 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 process. You can use the init_daemon function to generate your own daemon process. 1. init. c LIST # include <unistd. h> # include <signal. h> # include <sys/Param. h> # include <sys/types. h> # include <sys/STAT. h> void init_daemon (void) {int PID; int I; If (pid = fork () Exit (0); // It is the parent process, stop the parent process else if (PID <0) Exit (1); // fork failed, exit // is the first sub-process, and the background continues to execute setsid (); // The first sub-process becomes the new session leader and process leader // and is separated from the control terminal if (pid = fork () Exit (0); // is the first sub-process, stop the first sub-process else if (PID <0) Exit (1); // fork failed, exit // is the second sub-process, continue // the second sub-process is no longer the session leader For (I = 0; I <nofile; ++ I) // close the opened file descriptor close (I); chdir ("/tmp "); // change the working directory to/tmp umask (0); // reset the file to create the mask return;} 2. test. c LIST # include <stdio. h> # include <time. h> void init_daemon (void); // daemon initialization function main () {file * FP; time_t t; init_daemon (); // initialize to daemon while (1) // test every minute. log reports the running status {sleep (60); // If (FP = fopen ("test. log "," A ")> = 0) {T = time (0); fprintf (FP," Im here at % Sn ", asctime (localtime (& T); fclos E (FP) ;}} the above program is compiled under RedHat linux6.0. The procedure is as follows: Compile gcc-g-o Test init. C test. c execution :. /test view process: PS-Ef Description: there is a library function in the system call library that can directly turn a process into a daemon process, # include <unistd. h> int daemon (INT nochdir, int noclose );

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.