Programming implementation of the Linux daemon

Source: Internet
Author: User

programming methods for the Linux daemon

a daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons are a very useful process. Most Linux servers are implemented with daemons. For example, the Internet server Inetd,web server httpd and so on. At the same time, the daemon completes many 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's attention that copying some of the rules of the book (especially BSD4.3 and the lower version of System V) to Linux will be wrong. Below is a full description of the programming essentials of the Linux daemon and gives a detailed example.
A. Daemon and its characteristics
The most important feature of the daemon is running in the background. At this point, the resident memory program in DOS is similar to the TSR. Second, the daemon must be isolated from the environment before it runs. These environments include file descriptors that are not closed, control terminals, session and process groups, working directories, 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 performed by the user terminal (usually the shell).
in short, despite these peculiarities, daemons are basically no different from ordinary processes. Therefore, the process of writing a daemon is actually transforming a normal process into a daemon based on the nature of the daemon described above. It is easier to understand and program if the reader 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 principle is the same, the difference is that the specific implementation details are different. The principle is to satisfy the nature of the daemon. At the same time, Linux is based on Syetem v SVR4 and follows the POSIX standard, which is more convenient than BSD4. Programming essentials are as follows;
1. Run 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 terminals, logon sessions and process groups are usually 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. Due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal at the same time.
3. Disable process re-opening control terminal
now, the process has become a session leader without terminal. But it can be re-applied to open a control terminal. You can prevent a process from reopening the control terminal 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 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 where the process is located to fail to unload and cause unexpected errors. Close them as follows:
for (i=0;i Close Open file descriptor Close (i);>
5. Change the current working directory
The file system in which the working directory resides cannot be unloaded while the process is active. It is generally necessary to change the working directory to the root directory. For processes that require dump cores, the process that writes the log changes the working directory to a specific directory 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 modify 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
processing SIGCHLD signals is not a must. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If 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. If the parent process waits for the child process to end, it increases the burden on the parent process and affects 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 before releasing 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 the running state 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 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 separation from 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
//second child process is no longer a conversation leader

for (i=0;i< nofile;++i)//Close Open File descriptor
Close (i);
chdir ("/tmp");//Change Working directory 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 running 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. The steps are as follows:
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.

Googel, by the way, found a good website ite's edu:

http://www.iteedu.com/database/sqlite/

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.