Programming implementation of the Linux daemon

Source: Internet
Author: User
Tags tmp folder

Programming methods for the Linux daemon

A daemon (Daemon) is a special process that executes in the background. It is independent of the control terminal and periodically performs some sort of task or waits for some event to occur. Daemons are a very practical process. Most of Linux's servers are implemented with daemon processes. For example, internetserverinetd,webserverhttpd and so on. At the same time, the daemon finishes a lot of system tasks. For example, the job planning process Crond, the printing process lpd, and so on.
The daemon programming itself is not complex, the complexity of the various versions of UNIX implementation mechanism is not the same, resulting in different UNIX environment daemon programming rules are not consistent. This requires the reader to note that copying some of the rules of the book (especially the BSD4.3 and the lower version of System V) to Linux will cause errors. The following is a comprehensive introduction to the programming Essentials of the Linux daemon and gives specific examples.
A Daemon and its characteristics
The most important feature of the daemon is the background execution. At this point, the resident memory program in DOS is similar to a TSR. Second, the daemon must be isolated from the environment before its execution. These environments contain non-closed file descriptors, control terminals, session and process groups, working folders, and file creation masks. These environments are typically inherited by daemons from the parent process that executes it, especially the shell. Finally, the way the daemon is launched has its special place. It can be started from the startup 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 (typically the shell).
In short, despite these peculiarities, the daemon is basically no different from the normal process. Therefore, the process of writing a daemon is actually transforming a normal process into a daemon based on the nature of the daemons described above. It is easier to understand and program the reader if it has a deeper understanding of the process.
Two Programming Essentials for Daemons
As mentioned earlier, the programming rules for daemons in different UNIX environments are not consistent. Fortunately, the Daemon programming principles are all the same, and the difference lies in the specific implementation details. The principle is to satisfy the nature of the daemon. At the same time, Linux is based on the Syetem v SVR4 and follows the POSIX standard, which makes it easier to achieve than BSD4. Programming essentials such as the following;
1. Execute in the background.
To avoid suspending the control terminal, put the daemon into the background. The method is to call fork in the process to terminate the parent process, allowing Daemon to execute in the background in the child process.
if (Pid=fork ())
Exit (0);//is the parent process that ends the parent process, and the child process continues
2. Out of control terminal, logon session and process group
It is necessary to introduce the relationship between the process and the control terminal in Linux, 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 of the creation process.
Control terminal, logon sessions and process groups are generally inherited from the parent process. Our aim is to get rid of them so that they are not affected by them. The method is based on the 1th, call Setsid () to make the process a conversation leader:
Setsid ();
Description: The Setsid () call failed when the process was the session leader. But the 1th has ensured that the process is not a 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 of the exclusive nature of the session process to the control terminal, the process is detached from the control terminal at the same time.
3. Prohibit the process from opening the control terminal again
Today, the process has become a non-terminal conversation leader. But it can apply again to open a control terminal. Prevents a process from opening the control terminal again by making the process no longer a session leader:

if (Pid=fork ())
Exit (0);//End first child process, second child process continue (second child process is no longer a conversation leader)
4. Close the Open file descriptive descriptor
The process inherits the open file descriptive descriptor from the parent process that created it. Without shutting down, system resources will be wasted, causing the file system where the process is located to fail to unload and cause unexpected errors. Close them as in the following ways:
For (i=0;i Close open file descriptive narrator close (i);>
5. Change the current working folder
The file system on which the working folder resides cannot be unloaded while the process is active. It is generally necessary to change the working folder to the root folder. For a dump core, the process of writing the execution log changes the working folder to a specific folder such as/tmpchdir ("/")
6. Resetting the file creation mask
The process inherits the file creation mask from the parent process that created it. It may alter the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared: umask (0);
7. Handling SIGCHLD Signals
It is not necessary to process the SIGCHLD signal. However, for some processes, especially server processes, it is often necessary to generate child processes to process requests when a request arrives. Assuming that the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. Assuming the parent process waits for the child process to end, the burden of the parent process is added, affecting the concurrency performance of the server process. The operation of the SIGCHLD signal can be easily set to Sig_ign under Linux.
Signal (sigchld,sig_ign);
This way, the kernel does not spawn a zombie process at the end of the child process. Unlike BSD4, the BSD4 must explicitly wait for the child process to end its ability to release the zombie process.
Three Daemon Process Instance
The daemon instance consists of two parts: the main program TEST.C and the initialization program INIT.C. The main program reports execution status to the log test.log in the/tmp folder 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 parent process, end parent process
else if (pid< 0)
Exit (1);//fork failed, exit
Is the first child process, the background continues to execute
Setsid ();//first child process becomes new conversation leader and process leader
and separated from the control terminal
if (Pid=fork ())
Exit (0);//is the first child process, ending the first child process
else if (pid< 0)
Exit (1);//fork failed, exit
Is the second child process, continue
The second child process is no longer a conversation leader

for (i=0;i< nofile;++i)//Close Open File descriptive descriptor
Close (i);
ChDir ("/tmp");//Change working folder to/TMP
Umask (0);//Reset File creation 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 ();//Initialize to Daemon

while (1)//Report execution status to Test.log every minute
{
Sleep (60);//sleeping for one minute
if ((Fp=fopen ("Test.log", "a")) >=0)
{
T=time (0);
fprintf (FP, "Im here at%s/n", Asctime (LocalTime (&t)));
Fclose (FP);
}
}
}
The above program is compiled and passed under Redhat Linux6.0. Procedures such as the following:
Compilation: Gcc-g-O test init.c test.c
Execution:./test
View process: Ps-ef
The various features of the test daemon can be found from the output to meet the requirements above.

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.