A brief analysis of the programming method of Linux Daemon Course

Source: Internet
Author: User
Tags sessions

Daemon, which is usually called the daemon process, is the background service process in Linux. It is a long-running process that is usually independent of the control terminal and periodically performs a task or waits to handle certain occurrences. The daemon is often started during system boot loading and terminates when the system shuts down. The Linux system has many daemons, most of which are implemented through daemons, and the daemon can do many of the system tasks, such as the job planning process Crond, the print process LQD, and so on (the end letter D here is the meaning of daemon).

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. This requires the reader to note that copying some of the rules of the book (especially BSD4.3 and the lower version of System V) to Linux can be a mistake. The following is a comprehensive description of the Linux daemon's Programming essentials and gives a detailed example.

A Daemon processes and their characteristics


The most important feature of the daemon is running in the background. At this point the DOS Resident memory program is similar to the TSR. 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). 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. It is easier to understand and program if the reader has a deeper understanding of the process.

two. Key to the daemon's programming

As I mentioned before, the rules for the 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. 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. Out of control terminals, login sessions and process groups

It is necessary to introduce the process and control terminal in Linux, the relationship between the logon session and the process group: the process belongs to a process group, and the process group number (GID) is the process number (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 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, calling 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. Disable process Reopen control terminal

Now, the process has become a session leader without terminals. 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);//End first child process, second subprocess continue (second subprocess is no longer session leader)

4. Close the Open file descriptor

The 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. Change the current working directory

The file system in which the working directory resides cannot be unloaded when the process is active. 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 ("/") for the need to dump the core.

6. Reset File Creation Mask

The 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 SIGCHLD Signal

Processing of SIGCHLD signals 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 Daemon instance


The 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. The Init_daemon function in the initialization program 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 failed, quit
Is the first child process, the background continues to execute

Setsid ()//The first child process becomes the new session leader and process leader
and separated from the control terminal
if (Pid=fork ())
Exit (0);//is the first child process that ends the first child process
else if (pid< 0)
Exit (1);//fork failed, quit
Is the second child process, continue
The second subprocess is no longer the session leader

for (i=0;i< nofile;++i)//Close Open File descriptor
Close (i);
ChDir ("/tmp");//Change Working directory to/TMP
Umask (0);//reset File Create 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 report running status to Test.log
{
Sleep (60);//sleeping for one minute
if ((Fp=fopen ("Test.log", "a")) >=0)
{
T=time (0);
fprintf (FP, "I ' m here%sn", Asctime (LocalTime (&t)));
Fclose (FP);
}
}
}

The above program is compiled and passed under Redhat Linux6.0. The steps are as follows:
Compiling: Gcc–g–o test init.c test.c
Execution:./test
To view the process: Ps–ef
The various features of the test daemon can be found from the output to meet the above requirements.

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.