Linux C daemon Authoring

Source: Internet
Author: User
Tags local time

 The Linux programming-Daemon Authoring 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.    It is important to note that copying some of the rules of the book (especially BSD4.3 and the lower version of System V) to Linux will cause errors. The following is a combination of some predecessors ' documentation and their own examples of daemon programming: basic concepts. Process. Each process has a parent process. When a child process terminates, the parent process is notified and can get the child process's exit status: The process group. Each process also belongs to a process group. Group number, which is equal to the PID number of the group leader of the process. A process can only set the process group ID number for itself or a child process. Session duration. The conversation period is a collection of one or more process groups: the Setsid () function can establish a conversation period if the process of calling Setsid    is not the leader of a process group, this function creates a new session period.    (1) This process becomes the first process of the conversation (2) This process becomes the lead process for a new process group.    (3) This process does not control the terminal, if the process has a control terminal before calling Setsid, then the connection with the terminal is lifted.    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, the child process inherits the process group ID of the parent process, but the process PID is newly allocated, so it is not possible to be a new session of the PID of the process group.    thus guaranteeing this.    if ((Pid=fork ()) >0)//parent exit (0);           else if (pid==0) {//th1 child setsid (); Th1 is a session leader if (fork () ==0) {//th2 will not be a sessionTeam Leader (Orphaned process group) ...} A Daemon and its characteristics (1) 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. (2) Second, the daemon must be isolated from the environment before it is run. 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. (3) Finally, the daemon's startup mode 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. Two Programming Essentials for Daemons (from Ueap) before, the programming rules for daemons in different UNIX environments are inconsistent. 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. The programming points 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. From the control terminal, the logon session and process group processes belong 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. Because the session processThe control terminal is exclusive and the process is detached from the control terminal at the same time. 3. Prohibit the process from reopening the 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); Ends the first child process, the second child process continues (the second child process is no longer a session leader) 4. Closing the open file descriptor 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. The file system on which the working directory resides cannot be removed when the current working directory process activity is changed.    It is generally necessary to change the working directory to the root directory. For the process that needs to dump the core, the write run log changes the working directory to a specific directory such as/tmpchdir ("/") 6. The Reset file creation mask 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.    Processing SIGCHLD signal Processing SIGCHLD signal is not necessary.    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    The Daemon instance 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. //------------------------------------------------------------------------
#include <unistd.h>#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <sys/param.h>#include <sys/types.h>#include <sys/stat.h>#include <time.h>voidInit_daemon () {IntpidIntI;pid=Fork ();if (pid<0) Exit (1);//Create Error, exitElseif (pid>0)//The parent process exits exit (0); Setsid ();//Make child process leader pid=Fork ();if (pid>0) Exit (0);//Exit again so that the process is not the leader, so the process does not open the control terminalElseif (pid<0) Exit (1);//Closing a process open file handlefor (i=0;i<nofile;i++) Close (i); ChDir ("/root/test");//Change Directory Umask (0);//Reset the mask created by the fileReturn;}voidMain () {FILE *fp time_t T; Init_daemon ();While1) {Sleep (60); // Wait one minute and write Fp=fopen (testfork2.log" a "if (Fp>=0t); fprintf (Fp, "current time is:%s\n // Convert to local time output  fclose (FP);} return;}        

Run the following command:

CC Testfork2.c-o TESTFORK2

./testfork2

Ps-ef|grep TESTFORK2 can find the corresponding process.

Kill-9 1231 Kill Process

Turn (Reference): http://blog.csdn.net/zg_hover/article/details/2553321

Linux C daemon Authoring

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.