) Analysis of daemon principles and use of daemon functions in Linux

Source: Internet
Author: User

Which of the following isThe principle of daemon is not so troublesome in Linux, but it is still necessary.. From: http://www.cppblog.com/tx7do/articles/5963.html

Programming Method of the Linux daemon

Daemon is a special process running in the background. It is independent of the control terminal and periodically executes certain tasks or waits for some events to be handled. Daemon is a very useful process. Most Linux servers are implemented using daemon. For example, the Internet server inetd and the Web Server httpd. At the same time, the daemon completes many system tasks. For example, job planning process crond and printing process LPD.
Programming book of the daemon
The architecture is not complex. The complex architecture is that the implementation mechanisms of different versions of UNIX are different, resulting in inconsistent programming rules of daemon in different UNIX environments. This requires the reader to copy the rules in some books.
(Especially in bsd4.3 and earlier versions of System V) errors may occur in Linux. The following describes the programming points of the daemon in Linux and provides detailed examples.

1. daemon process and Its Features

Shoushou
The most important feature of the protection process is the background operation. At this point, the resident memory under DOSProgramSimilar to tsr. Second, the daemon must be isolated from the environment before running. These environments include files not closed
File descriptor, control terminal, session and process group, working directory, and file creation mask. These environments are generally inherited by the daemon from the parent process (especially the shell) that executes the daemon. Finally, daemon
The process startup method has its own special characteristics. It can be started from the startup script/etc/rc. d when the Linux system is started. It can be started by the job planning process crond or the user terminal.
(Usually shell) execution.

In short, apart from these special features, the daemon process is basically no different from the common process. Therefore, writing a daemon actually transforms a common process into a daemon according to the features of the preceding daemon. If you have a deep understanding of the process, it is easier to understand and program the process.

II. Key Points of daemon Programming

Before
As mentioned above, the programming rules of daemon in different UNIX environments are inconsistent. Fortunately, the programming principles of the daemon process are the same. The difference is that the specific implementation details are different. This principle is to satisfy the requirements of the guardian
Feature. At the same time, Linux is a svr4 Based on syetem V and complies with the POSIX standard, which is easier to implement than bsd4. The main points of programming are as follows;

1. Shield some signals related to control terminal operations.
This is to prevent the control terminal from being disturbed and exited or suspended when the daemon process is not running properly. Example:

 
Signal (sigttou, sig_ign );
Signal (sigttin, sig_ign );
Signal (sigtstp, sig_ign );
Signal (sighup, sig_ign );

All signals have their own names. These names all start with "sig", but they are different later. Developers can use these names to learn about what happened in the system. When the signal appears, developers can ask the system to perform the following three operations:

Ignore the signal. Most signals are processed in this way. However, it is worth noting that the sigkill and sigstop signals cannot be ignored.

Capture signals. The most common condition is that if the sigchid signal is captured, the sub-process has been terminated. Then, you can call the waitpid () function in the capture function to obtain the sub-process.
Process ID and its termination status. In addition, if a process creates a temporary file, you need to write a signal capture function for the Process Termination signal sigterm to clear these temporary files.
Executes the default action of the system. For the vast majority of signals, the default action of the system is to terminate the process. Generally, the signals of these terminals are neglected to protect the terminals from interference.
These signals are: sigttou (indicating the background process write control terminal), sigttin (indicating the background process read control terminal), and sigtstp (indicating that the terminal is suspended) and sighup (sent to all meeting members when the process leader exits ).

2. Run in the background.
To avoid pending the control terminal, place the daemon in the background for execution. The method is to call fork in the process to terminate the parent process and run daemon in the background of the child process.

If (pid = fork ())
Exit (0); // indicates the parent process. The parent process ends and the child process continues.

3. log on to the session and process group from the control terminal.
It is necessary to first introduce the relationship between processes and control terminals, logon sessions, and process groups in Linux: Processes belong to a process group, process group number (GID) is the process ID (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 that creates a process.
Control terminal, logon sessions and process groups are generally inherited from the parent process. Our goal is to get rid of them so that they are not affected. The method is to call setsid () on the basis of to make the process a session leader:

Setsid ();

Note: setsid () fails to be called when the process is a session leader. However, the first point is that the process is not the session leader. After the setsid () call is successful, the process becomes a new session leader and a new process leader, and is detached from the original logon session and process group. Because the session process is dedicated to the control terminal, the process is separated from the control terminal at the same time.

4. Prohibit the process from re-opening the control terminal
Now, the process has become the no-end session leader. But it can re-apply to open a control terminal. You can disable the process from re-opening the control terminal by making the process no longer the session leader:

If (pid = fork ())
Exit (0); // end the first child process and the second child process (the second child process is no longer the session leader)

5. Disable open file descriptors
A process inherits the opened file descriptor from the parent process that created it. If you do not close it, system resources will be wasted, and the file system where the process is located will not be able to be detached and unexpected errors will occur. Close them as follows (nofile is defined in the header file ):

For (I = 0; I <nofile; I ++)
Close (I );

6. Change the current working directory
When a process is active, the file system of its working directory cannot be detached. Generally, you need to change the working directory to the root directory. For processes that need to dump the core, write the running log to change the working directory to a specific directory, such as/tmp:

Chdir ("/tmp ")

7. Reset the file to create a mask
A 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, clear the file creation mask:

Umask (0 );

8. Process sigchld Signal
Location
The sigchld signal is not necessary. However, some processes, especially server processes, usually generate sub-processes to process requests when requests arrive. If the parent process does not wait until the child process ends, the child process becomes stiff
Zombie occupies 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 concurrent performance of the server process. In Linux
The operation of sigchld signal is set to sig_ign.

Signal (sigchld, sig_ign );

In this way, the kernel will not generate zombie processes when the child process ends. This is different from bsd4. In bsd4, you must explicitly wait for the child process to end before releasing the zombie process.

Which of the following isHow to Use daemon to implement daemon in Linux, From: http://sirius.gnu.blog.163.com/blog/static/14683368020103733027574/

 

Use the daemon function in Linux to write background programs

2010-04-07 15:30:27| Category:Default category |Font Size Subscription

In the past, when we were reading "Advanced Programming in UNIX environments", we had a special whole chapter detailing how to compile a background daemon program (genie Program), mainly involving creating session groups, switch the working directory, set the file blocking characters, and disable unnecessary Descriptor and other operations. These operations are similar for every background program.

In Linux, a function is provided to complete the daemon process. The prototype of this function is as follows:

 
IntDaemon(Int_ Nochdir, Int_ Noclose);

If the value of _ nochdir is 0, the working directory is switched to the root directory. If _ noclose is 0, the standard input is made, both output and standard errors are redirected to/dev/null.

After this function is called, the program runs in the background and becomes a daemon program. Most services in Linux run in this way.

Let's look at a simple example. For example, compile the example program test. C.

 # Include <unistd. h> 
# Include <stdio. h>

Int Do_something ( )
{
// Add what u want
Return 0 ;
}
Int Main ( )
{
Daemon ( 0 , 0 ) ;
While ( 1 )
{
Do_something ( ) ;
Sleep ( 1 ) ;
}
}

Compile and run

[Leconte@Localhost daemon]$Gcc -O TestTest. c
[Leconte@Localhost daemon]$./Test

The program enters the background and displays the Process status through PS. The parent process ID of the process is 1, that is, the INIT process.

Use lsof to view the files opened by the test process. The file descriptors 0, 1, and 2 are redirected to/dev/null.

We can also see that the current working directory (CWD) of the process is the root directory/, and the daemon function has helped us complete the daemon process. Next we only need to focus on the implementation of program functions.

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.