Linux daemon and daemon

Source: Internet
Author: User

Linux daemon and daemon

I. Introduction

In a linux or unix operating system, many services are enabled during system boot. These services are called daemon processes. The daemon is disconnected from the terminal and runs in the background: the daemon is separated from the terminal to prevent the information in the execution process from being displayed on any terminal and the process is not interrupted by any terminal information generated by any terminal.

The programming of daemon is not complex. The complicated problem is that different versions of Unix have different implementation mechanisms, resulting in inconsistent programming rules of daemon in different Unix environments. This requires you to note that copying the rules in some books (especially BSD4.3 and earlier versions of System V) will cause errors to Linux. The following describes the programming points of the daemon in Linux and provides detailed examples.

Ii. Features of daemon

1) The most important feature of the daemon is that it runs in the background.

2) The Daemon must be isolated from its running environment.

These environments include unclosed file descriptors, control terminals, sessions and process groups, working directories, and file creation masks. These environments are generally inherited by the daemon from the parent process (especially the shell) that executes the daemon.

3) the startup method of the daemon has its own 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 and executed by the user terminal (usually shell.

 

3. Daemon programming steps

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 characteristics of the daemon process. 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) 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); // It is the parent process, ends the parent process, and the child process continues

2) log on to the session and process group from the control terminal

The relationship between processes and control terminals in Linux, logon sessions, and process groups: Processes belong to a process group, and the 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: After setsid () is successfully called, 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.

3) 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)
4) disable the opened file descriptor.

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:

For (I = 0; I <NOFILE; ++ I) // close the opened file descriptor close (I );

5) 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("/");

6) 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);

7) process SIGCHLD Signal

It is not necessary to process SIGCHLD signals. However, some processes, especially server processes, usually generate sub-processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process will become a zombie process, occupying 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, you can set the SIGCHLD signal operation 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.

 

4. Daemon instance

The daemon instance consists of 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 process. You can use the init_daemon function to generate your own daemon process.

//init.c
# Include <stdlib. h> # 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); // It is the parent process, stop the parent process else if (pid <0) exit (1); // fork failed, exit // is the first sub-process, and the background continues to execute setsid (); // The first sub-process becomes the new session leader and process leader // and is separated from the control terminal if (pid = fork () exit (0); // is the first sub-process, stop the first sub-process else if (pid <0) exit (1); // fork failed, exit // is the second sub-process, continue // the second sub-process is no longer the session leader for (I = 0; I <NOFILE; ++ I) // close the opened file descriptor close (I ); chdir ("/tmp"); umask (0); // reset the file creation mask return ;}

 

//test.c
# 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) // test every minute. log reports the running status {sleep (60); // if (fp = fopen ("test. log "," a ")> = 0) {t = time (0); fprintf (fp," I'm here at % s \ n ", asctime (localtime (& t); fclose (fp );}}}

Compile

gcc –g –o test init.c test.c

Run

./test

View

ps -rf | grep test

 

Reference: http://www.w2bc.com/Article/22124

Related Article

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.