The principle and implementation of the Linux daemon

Source: Internet
Author: User

I. Overview of the daemon process

Many services are turned on in Linux or UNIX operating systems when the system is booted, and these services are called daemons. For added flexibility, root selects the system-enabled mode, which is called the RunLevel, and each runlevel configures the system in a certain way. Daemons are processes that are detached from the terminal and run in the background. The daemon is detached from the terminal to prevent the information in the process from being displayed on any terminal and the process will not be interrupted by terminal information generated by any terminal.

Ii. Overview of the daemon process

The daemon, which is usually called the daemon process, is the background service process in Linux. It is a long-lived process, usually independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons often start when the system boots, and terminate when the system shuts down. Linux systems have many daemons, most of which are implemented through daemons, while the daemon can accomplish many system tasks, such as the job planning process Crond, the printing process lqd, and so on (the end letter D is the daemon meaning).

Because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal will be attached to this terminal, this terminal is called the control terminal of these processes, when the control terminal is closed, the corresponding process will automatically shut down. But the daemon is able to break through this limitation, and it will start running from execution until the entire system shuts down. If you want a process to not be affected by changes in the user or terminal or otherwise, you must turn the process into a daemon.

Third, create the daemon process
  1. Create child process, parent process exits

    in Linux the parent process exits before the child process, which causes the child process to become an orphan process, and is automatically adopted by process 1th (INIT) When the system discovers an orphan process, so that The original subprocess becomes the child process of the INIT process.

  2. create a new session in a child process

    process group: is a collection of one or more processes. The process group has a process group ID to uniquely identify. In addition to the process number (PID), the process group ID is also a prerequisite property for a process. Each process group has a leader process, and the process number of its leader process equals the process group ID. And the process group ID will not be affected by the exit of the leader process.

    session period: The session period is a collection of one or more process groups. Typically, a session starts at the user logon and terminates when the user exits, during which all the processes that the user runs are part of the session period.

    • Let the process get rid of the control of the original session
    • let the process get rid of the control of the original process group
    • Let the process get rid of control of the original control terminal

    So why call the SETSID function when creating the daemon? Because the first step in creating the daemon calls the fork function to create the child process, and then exits the parent process. Because when the fork function is called, the child process copies the session period of the parent process, the process group, the control terminal, etc., although the parent process exits, but the session period, the process group, the control terminal and so on have not changed, so this is not the true sense of independence, and the SETSID function can make the process completely independent, So as to get rid of the control of other processes.

  3. Change the current directory to be the root target

    This step is also a necessary step. A child process created with fork inherits the current working directory of the parent process. Because the file system in which the current directory resides (such as "/mnt/usb") is not unloaded while the process is running, this can cause a lot of trouble for later use (such as the system entering single-user mode for some reason). Therefore, the usual practice is to let "/" as the current working directory of the Daemon, so as to avoid the above problems, of course, if you have special needs, you can also change the current working directory to other paths, such as/tmp. A common functional chdir that changes the working directory.

  4. Reset File Permission Mask

    The file permission mask refers to the corresponding bit in the file permission that is masked out. For example, there is a file permission mask of 050, which masks the file group owner's readable and executable permissions. Because the new child process using the Fork function inherits the file permission mask of the parent process, this creates a lot of trouble for the child process to use the file. Therefore, setting the file permission mask to 0 can greatly enhance the daemon's flexibility. The function that sets the file permission mask is umask. Here, the usual method of use is Umask (0).

  5. Close File descriptor

    As with the file permission code, a new child process with the fork function inherits some files that have already been opened from the parent process. These open files may never be read and written by the daemon, but they consume system resources as well, and may cause the file system in which they reside to fail to be unloaded. After the second step above, the daemon has lost contact with the owning control terminal. As a result, characters entered from the terminal cannot reach the daemon, and characters that are output by a regular method (such as printf) in the daemon cannot be displayed on the terminal. Therefore, 3 files with file descriptors of 0, 1, and 2 (often referred to as input, output, and error) have lost their existing value and should be closed. The file descriptor is typically closed as follows:

    [CPP] view plaincopy
    1. ===============================
    2. for (i=0;i<maxfile;i++)
    3. Close (i);
    4. ===============================
  6. Daemon Exit Processing

    When the user needs an external stop daemon to run, the kill command is often used to stop the daemon. Therefore, the daemon needs to encode to achieve the signal signal processing of kill, to achieve the normal exit of the process.

Iv. A complete example of the daemon (every 10s write a sentence in/tmp/dameon.log) [CPP]View Plaincopy
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <sys/types.h>
  6. #include <unistd.h>
  7. #include <sys/wait.h>
  8. #include <signal.h>
  9. #define Maxfile 65535
  10. Volatile sig_atomic_t _running = 1;
  11. void Sigterm_handler (int arg)
  12. {
  13. _running = 0;
  14. }
  15. int main ()
  16. {
  17. pid_t pc, PID;
  18. int i, FD, Len;
  19. char *buf = "This is a dameon\n";
  20. Len = strlen (BUF);
  21. //First step
  22. PC = fork ();
  23. if (PC < 0)
  24. {
  25. printf ("error fork\n");
  26. Exit (1);
  27. }
  28. Else if (PC > 0)
  29. {
  30. Exit (0);
  31. }
  32. //Second step
  33. Setsid ();
  34. PID = fork (); //Complete disengagement from the terminal [1]
  35. if (PID < 0)
  36. {
  37. Perror ("fork Error");
  38. }
  39. if (PID > 0)
  40. {
  41. Exit (0);
  42. }
  43. //Step three
  44. ChDir ("/");
  45. //Fourth step
  46. Umask (0);
  47. //Fifth step
  48. For (i = 0;i < Maxfile; i++)
  49. {
  50. Close (i);
  51. }
  52. Signal (SIGTERM, Sigterm_handler);
  53. While (_running)
  54. {
  55. if (fd = open ("/tmp/dameon.log", O_creat | o_wronly | O_append, 0600)) < 0)
  56. {
  57. Perror ("open");
  58. Exit (1);
  59. }
  60. Write (FD, buf, Len);
  61. Close (FD);
  62. Usleep (10 * 1000); //10 Ms
  63. }
  64. }

Transferred from: http://blog.csdn.net/zsf8701/article/details/8817510

The principle and implementation of the Linux daemon

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.