Linux Daemon Authoring __linux

Source: Internet
Author: User
Tags sessions
                             Linux Programming-Daemon process writing daemon (Daemon) is a special process running in the background. It is independent of the control terminal and periodically performs a task or waits to handle certain occurrences. 
    The daemon is a very useful process. Most of Linux's servers are implemented with daemon processes.
    For example, 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 print process LPD, and so on.
    The daemon's programming itself is not complex, and the complexity is that different implementations of UNIX are not the same, resulting in inconsistent programming rules for daemons in various UNIX environments.
    Note that it is wrong to copy some of the rules of the book (especially BSD4.3 and the lower version of System V) to Linux. The following combination of some of the predecessors of the documentation and their own examples of the Daemon program. Basic concepts. Process. Each process has a parent process. When a child process terminates, the parent process is notified and can take the child process's exit status. The process group. Each process also belongs to a process group.
    Process owners have a process group number, the number equals the PID number of the group leader of the process. A process can set the process group ID number only for itself or for a subprocess. Session period. Dialog is a collection of one or more process groups. The Setsid () function can establish a dialog period:
    If the process 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 session (2) the process becomes the leader of a new process group.
    (3) This process has no control terminal, if the process has a control terminal before calling Setsid, then the connection to the terminal is relieved.
    If the process is the leader of a process group, this function returns an error.
    (4) To ensure this, we first call fork () and exit (), at which 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 assigned, so it is not possible to be the PID of the process group for the new session.

    thus guaranteeing this.
    if ((Pid=fork ()) >0)//parent exit (0); else if (pid==0) {//th1 Child setsid ();
    Th1 is the session leader if (fork () ==0) {//th2 will not be the session leader (become an orphan process group) ...} A The most important feature of daemon and its characteristics (1) daemon is running in the background.
    At this point the DOS Resident memory program is similar to the TSR. (2) Second, the daemon must be isolated from its running environment. These environments include file descriptors that are not closed, control terminals, sessions and process groups, working directories, and file creation masks.
    These environments are typically inherited by the daemon from the parent process that executes it (especially the shell). (3) Finally, the way the daemon is started has its own special place.
  It can be started from the boot script/ETC/RC.D when the Linux system starts, can be started by the job planning process Crond, and can be executed by the user terminal (usually the shell).
    In short, in addition to these particularities, daemons are basically no different from ordinary processes.

Thus, writing a daemon is actually transforming a common process into a daemon by following the characteristics of the daemons described above. Two The main point of the Daemon's programming (from Ueap) is that the programming rules for daemons in different UNIX environments are inconsistent. Fortunately, the Daemon programming principles are all the same, 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 based on the SVR4 of Syetem V and follows the POSIX standard, which is more convenient to achieve compared with BSD4. The programming essentials are as follows; 1.
  Run in the background. To avoid suspending the control terminal to put daemon into the background execution.

The method is to call fork in the process to terminate the parent process, allowing the daemon to execute in the background in the child process. if (Pid=fork ()) exit (0); Is the parent process, ending 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, and the process group number (GID) is the process leader's process number (PID).
    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 the process.
    Control terminals, logon sessions and process groups are usually inherited from the parent process.
    Our aim is to get rid of them from their influence.

  The method is based on the 1th, invoking Setsid () to make the process the session leader: Setsid ();Description: The SETSID () call fails when the process is the session leader.
    But the 1th has ensured that the process is not the 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 process is exclusive to the control terminal, the process is also detached from the control terminal. 3. Prohibit the process from reopening the control terminal now, the process has become a session leader without terminal.
    But it can reapply to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer the session leader: if (Pid=fork ()) exit (0); Ends the first child process, the second subprocess continues (the second subprocess is no longer the session leader) 4. Closes 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 in which the process is located to fail to unload and cause unexpected errors. Close them as follows: for (I=0;i closes the open file descriptor Close (i);> 5. When changing the current working directory process activity, the file system where the working directory resides cannot be removed.
    It is generally necessary to change the working directory to the root directory. The process for the write run log changes the working directory to a specific directory such as/tmpchdir ("/") 6 for the need to dump the core. 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, create a mask purge of the file: Umask (0);
    7. Processing of SIGCHLD signal processing SIGCHLD signal is not necessary.
    However, for some processes, especially server processes, it is often necessary to generate a subprocess processing request when the request arrives.
    If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) that consumes 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 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 produce a zombie process at the end of the subprocess.

Unlike BSD4, 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 status to the log test.log in the/tmp directory every minute. In the initialization programThe Init_daemon function 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 > void Init_daemon (void) {int pid;
    int i;        if (Pid=fork ()) exit (0);        Is the parent process, ending the parent process else if (pid< 0) exit (1);           Fork failure, exit//is the first child process, the background continues to execute setsid ();        The first child process becomes the new session leader and process leader//and separates the IF (Pid=fork ()) exit (0) from the control terminal;        Is the first child process that ends the first subprocess else if (pid< 0) exit (1);

    Fork failed, exit//is second subprocess, continuation//second subprocess is no longer session leader for (i=0;i< nofile;++i)//closes open file descriptor close (i);      ChDir ("/tmp");           Change working directory to/TMP umask (0);
Reset file creation 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 ()//initialized to Daemon while (1)/Every minute to Test.log report run state {sleep (60);A minute if ((Fp=fopen ("Test.log", "a")) >=0) {t=time (0);
            fprintf (FP, "Im here%sn", Asctime (LocalTime (&t)));
        Fclose (FP); The above program is compiled and passed under Redhat Linux6.0. The steps are as follows: Compile: gcc-g-o test init.c test.c execution:./test View Process: Ps-ef Note: There is a library function in the system call library that can directly turn a process into a daemon, #include <unistd.





 h> int daemon (int nochdir, int noclose);
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.