Little talk process: Write Linux daemon method

Source: Internet
Author: User

Guardian Process Overview
The daemon, which is commonly referred to as the daemon process, is a 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 for the occurrence of certain events to be handled.
Daemons often start when the system boots, and terminate when the system shuts down.

Linux has a lot of system services, and most of the services are implemented through daemon processes. The name of the daemon usually ends with D, and the letter D is the meaning of daemon.

Because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal is attached to this terminal, this terminal is called the control terminal of these processes.
When the control terminal is closed, the corresponding process will be automatically closed.
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 be unaffected by user, terminal, or other changes,

Then you have to turn this process into a daemon. It can be seen that the daemon is very important.


Daemon Features
Running
in the background: this is the most important feature of the daemon process.
The daemon must be isolated from the environment before it runs: These environments are inherited from the parent process (or shell) that started it, including: control terminals, session and process groups, file descriptors that are not closed, working directories, and file creation masks.
The Daemon's start-up is special: It can be started from startup script/etc/rc.d at system startup, can be started by the inetd daemon, can be started by the job planning process Crond, and can be performed by a user terminal (usually a shell).


(1). Create child process, parent process exits--out of control terminal


Daemon is out of control terminal. Completing the first step creates a false illusion that the program has finished running in the shell terminal. All subsequent work is done in the sub-process, and the user can execute other commands in the shell terminal to disengage from the control terminal in form.
The parent process exits after the child process is created, causing the child process to have no parent process, thus making the child process an orphan process.
In Linux, whenever the system discovers an orphan process, it is automatically adopted by the 1th process (that is, the init process), so that the original subprocess becomes a child of the INIT process. The key code is as follows:

PID = fork (), if (PID > 0) {    


(2). Create a new session in a child process--a conversation group and a process group that is out of the parent process


This step is the most important step in creating the daemon, although its implementation is very simple, but its significance is very significant: to make the process completely independent, so as to disengage from all other processes of control.
Method: Call the System function Setsid (), create a new session period, and make the process calling the SETSID function the first process of the new session, and detach from the session group and Process Group of its parent process to become the first process of a new process group.
Process Group:
A process group is a collection of one or more processes. The process group is uniquely identified by the process group ID. 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 ID will not be affected by the exit of the leader process.


Session Period:
A 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 belong to this session period, and the relationship between them is as follows:



(1) Setsid () function
Because when the fork () function is called, the child process replicates the session duration of the parent process, the process group and the control terminal, etc., although the parent process exits, but the original session, process group, and control terminal are not changed, so it is not really independent, and the Setsid () function can make the process completely independent , thus leaving the control of all other processes as a background process.

If the process is not the leader of a process group, calling Setsid () has the following 3 functions.
Create a new session that allows the process to get rid of the control of the original conversation and become the first process of the new conversation group.
Create a new process group that allows the process to get rid of the control of the original process group and become the first process of a new process group.
Let the process get rid of the original control Terminal control, become a background process.


(2) Setsid () function format



3. Change the current directory of the process to the root directory
Child processes created with fork () inherit the current working directory of the parent process. Because the file system in which the current directory resides (such as "/MNT/USB", etc.) cannot be unloaded while the process is running,

This can cause a lot of trouble for later use (for example, the system goes into single-user mode for some reason).
The usual practice is to let "/" as the current working directory of the Daemon, so that the above problems can be avoided, of course, if there is a special need, you can also change the current working directory to other paths, such as/tmp.
The common function for changing the working directory is chdir ().


4. Reset file permission mask to 000
The file permission mask is used to control the default properties of the generated file, and its purpose is to mask the corresponding bits in the file permissions. For example, the file permission mask is 050, it blocks the file group user's R and X 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, set the file permission mask to 0,

Can greatly enhance the flexibility of this daemon.
The function that sets the file permission mask is Umask (). When you create a daemon, the usual method is Umask (0).


5. Close File descriptor
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 or written by the daemon, but they consume system resources just as much.

It is also possible that the file system in which it resides cannot be uninstalled.
Exactly which descriptors to close is related to the specific daemon, it is necessary to close the 0, 1, 23 file descriptors, standard input, standard output, standard error.

After the second step, 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 have lost their existing value and should be closed. The file descriptor is typically closed as follows:

for (i = 0; i < maxfile; i++) {      close (i);}

to create a daemon process:


Example:

Here is a complete instance of the implementation daemon, which first establishes a daemon based on the above creation process, and then lets the daemon write a sentence to the log file/tmp/daemon.log every 10s.

/* Create Daemon instance */#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h># Include<sys/types.h> #include <sys/wait.h>int main () {pid_t pid;int i,fd;char* buf= "This is a daemon\n";p id= Fork ();//Create Child process if (pid<0) {printf ("Error fork\n"); exit (1);} else if (pid>0) {exit (0);//exit Parent process}setsid ();//Create New Session chdir ("/") in child process,//change current directory to working directory Umask (0);//reset file permission mask for (i=0;i< Getdtablesize (); i++)//close file descriptor {close (i);} while (1) {if (Fd=open ("/tmp/daemon.log", o_creat| o_wronly| o_append,0600)) < 0) {printf ("Open file error! \ n "); exit (1);} Write (FD, buf, strlen (BUF) +1); close (FD); sleep (10);} Exit (0); return 0;}

Run as follows:



You can see that the program will enter relevant content in the corresponding file every 10s. And using PS, you can see that the process is running in the background.

Enter the command in the terminal:ps-ef|grep daemon


The results appear as follows:



Little Tricks

Tail Command: Writes the file to standard output starting at the specified point. Using the-f option of the tail command makes it easy to see the log files that are being changed, TAIL-F filename will display the most up-to-date content on the screen, and constantly refresh to keep you updated on the contents of the file.

Little talk process: Write Linux daemon method

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.