Linux multi-task programming seven: the Linux daemon and its basic experiment

Source: Internet
Author: User
Tags log log openlog syslog system log tmp folder

Source: CSDN Wang Wensong transferred from Linux commune

------------------------------------------------------------------------------------------------

Guardian Process Overview

Daemon, also known as the daemon process (somehow, I suddenly remembered the vampire Diary of Damon, very good-looking American drama), Linux is the background service process. He 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 has many systems, and most services are implemented through daemons. At the same time, the daemon can accomplish many system tasks, for example, the job planning process cronf, the printing process LQD, etc. (here the end letter D is the meaning of daemon).

In Linux, each system communicates with the user interface called the terminal , every process starting 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. However, the daemon is able to break through this restriction, and it starts running from execution until it receives a signal or the entire system shuts down before exiting. If you want a process to be unaffected by user, terminal, or other changes, you must turn the process into a daemon. It can be seen that the daemon is very important.

To write a daemon step

The authoring daemon follows a specific process, and the steps to create the daemon are explained below.

1. Create a child process, and the parent process exits.

This is the first step in the process of writing the daemon. Because the daemon is out of control terminal, so the completion of the first step in the shell terminal will cause a program has been running the illusion, after all the work is done in the child process, and the user in the shell terminal can execute other commands, in the form of control terminal to achieve the separation.

However, after the parent process has created the child process and exits, does the child process have no parent process at this time? There is a real interesting phenomenon in the daemon: because the parent process exits before the child process, it causes the child process to have no parent process and thus becomes an orphan process. In Linux, each time the system discovers an orphan process, it is automatically adopted by the 1th process (that is, the init process), so that the original child process becomes a child of the INIT process. The key code is as follows;

2. Create a new session in a child process

This step is the most important step in creating the daemon, although the implementation is very simple, but the meaning is very significant. The system function Setsid () is used here to understand the following two concepts before specifying SETSID (): Process groups and session periods.

The 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 PID of its leader process equals the process group ID, and the process group ID is not affected by the exit of the leader process. (The team leader has gone, and then find a team member to serve as group leader Bai)

Session period. A conversation group 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. Relationship 1 between the process group and session period is as follows:

The next step is to introduce the relevant content of Setsid ().

The role of the ①setsid () function. The Setsid () function is used to create a new conversation group and let the process executing this function serve as the leader of the conversation group. Call Setsid () has the following 3 functions:

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, go back and think about why you call the Setsid () function when you create the daemon. So, in the first step of creating the daemon, the fork () function is called to create the child process and then the parent process exits. Because when the fork () function is called, the child process replicates the session duration, the process group, and the control terminal of the parent process, and the parent process exits, but the original session, process group, and control terminal are not changed, so it is not really independent. The Setsid () function allows the process to be completely independent from the control of all other processes.

②setsid function format

3. Change the current directory to the root directory

This step is also a necessary step. Child processes created with fork () inherit the current working directory of the parent process. Due to the fact that the file system in which the current directory resides (such as "/MNT/USB", etc.) is not unloaded during the process, this can cause a lot of trouble for later use (e.g., the system needs to go into single-user mode for some reason). Therefore, it is common practice to have "/" as the current working directory of the daemon so that the above problems can be avoided. Of course, if you have special needs, you can also change the current working directory to another path, such as/tmp. The common function for changing the working directory is chdir ().

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 readable and executable permissions of the filegroup owner. 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 (). The usual method of use is Umask (0).

5. Close File descriptor

As with the file permission mask, new child processes with the fork () function inherit some files that have already been opened from the parent process. These files that are opened may never be read or written by the daemon, but they consume system resources as well, and may cause the file system that resides to fail to be uninstalled.

In fact, after the 2nd step above, the daemon has lost contact with the control terminal to which it belongs, so the characters entered from the terminal are not likely to reach the daemon, and the characters that are output by a regular method (such as printf ()) in the daemon cannot be displayed on the terminal. So the file descriptor is 0, 1 and 2 of 3 files (often said input/output and error of the 3 files) have lost the value of existence, should also be closed. Normally, close the file descriptor as follows:

See the blog about the role of Getdtables ():

Here, a simple daemon is set up. To create a flowchart for the daemon:

Basic experiments

This experiment builds a daemon based on the above creation process, and then lets the daemon write a sentence to the log file/home/song/tmp/daemon.log every 10s. program code as follows, I also upload to the site, click here to download

Let's take a look at the/tmp folder without Daemon.log.

After downloading the file, compile with the command: GCC dameon.c-o daemon

Then execute the command:./daemon you can see there's no change at this point.

Use the command: Ps-ef|grep./daemon use the keywords in PS to see if the system is currently running and there is no our daemon process

We can see that our daemon is already running, and look at the contents of the/tmp directory.

As you can see, there are already daemon.log log files.

Then use the command: Tail-f/tmp/daemonl.log, you can see that the program every 10s will be in the corresponding file input relevant content

Here, the experiment is over, using the command in front: Ps-ef|grep./daemon can see that we process the process number is 3346, now use the command: Kill-9 3346 to kill the process, but also TMP in the Daemon.log file page Delete, convenient for our experiment below.

Error handling of the daemon process

During the specific debugging process of the daemon, it is found that because the daemon is completely out of control terminal, the error information can not be output to the control terminal as other normal process, so the programmer can not be debugged even if GDB is used. So, how is the daemon process going to be debugged? A common approach is to use the Syslog service to enter error information from the program into the system log file (such as "/var/log/messages") so that you can visually see the problem with the program ("/var/log/message" System log files can only be viewed by superuser who has root privileges. In different Linux distributions, the full name of the system log file path may be different, for example, the path in my Ubuntu is "/var/log/syslog".

Syslog is a system log management service in Linux that is maintained by the daemon syslogd. The daemon reads a configuration file "/etc/syslog.conf" at startup, which determines where different kinds of messages are sent. For example, an emergency message can be sent to the system administrator and displayed on the console, while a warning message can be recorded in a file.

The mechanism provides 3 syslog-related functions, Openlog (), syslog (), and Closelog (), respectively, and these 3 functions are described below.

Function description

The Openlog () function is used to open a link to the System Log service; the syslog () function is used to write information to the log file, where you can set the priority of the message, the message output format, and so on; the Closelog () function closes the link to the System Log service.

function format

Basic experiments

We can try to execute the program in normal status (Redhat do not use Root,ubuntu to run properly). Because the open () function here must have root privileges, the Syslog writes error information to the System log file ("such as/var/log/syslog"), as shown in

This experiment file syslog_damen.c download

Free in http://linux.linuxidc.com/

User name and password are www.linuxidc.com

Specific download directory in/2013 information/June/12th/linux multitasking programming

Linux multi-task programming seven: Linux daemon and its basic experiment (GO)

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.