Linux programming-special process daemon and linux programming daemon

Source: Internet
Author: User

Linux programming-special process daemon and linux programming daemon
What is a daemon?

Daemon Process (Daemon Process) is a background service Process in Linux. It is a long-lived process, usually independent of the control terminal and periodically executes a task or waits to process some events.


A daemon is a special orphan process, which is separated from the terminal,Why do we need to leave the terminal?The reason for discontinuing from the terminal is to prevent the process from being interrupted by the information generated by any terminal, and its information during execution is not displayed on any terminal. In Linux, every system interface that communicates with users is called a terminal. Every process starting from this terminal is attached to this terminal, which is called the control terminal of these processes, when the control terminal is closed, the corresponding process is automatically closed.


Most Linux serversIs implemented by the daemon. For example, the Internet server inetd and the Web Server httpd.


View daemon

On the terminal: ps axj

  • A indicates that not only processes of the current user are listed, but also processes of all other users are listed.
  • X indicates that not only processes with control terminals are listed, but also processes with no control terminals are listed.
  • J indicates listing information related to job control.


We can see some features of the daemon:

  • The daemon process is basically started as a Super User (UID is 0)
  • No control terminal (TTY is ?)
  • The Terminal Process Group ID is-1 (TPGID indicates the Terminal Process Group ID)


Generally, daemon can be started in the following ways:

  • The startup scripts are usually placed in the/etc/rc. d directory when the system is started;
  • Use the inetd super server to start, such as telnet;
  • The process started by cron and started by nohup on the terminal is also a daemon process.

How to Write a daemon? The following is the basic process for compiling the daemon process: 1) Shield some control terminal operation Signals
This is to prevent the control terminal from being disturbed and exited or suspended before the daemon is running.
signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); signal(SIGTSTP,SIG_IGN); signal(SIGHUP ,SIG_IGN);

2) Run in the background
This is to prevent the control terminal from putting the daemon process into the background for execution. The method is to call fork () in the process to terminate the parent process and run the daemon in the background of the child process.
If (pid = fork () {// parent process exit (0); // end parent process, child process continues}

3) Disconnects control terminals, logon sessions, and Process Groups
It is necessary to introduce Relationship between processes and control terminals, logon sessions, and Process Groups: A process belongs to a process group. 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 shell login terminal that creates the process. The control terminal, logon session, and process group are inherited from the parent process. Our goal is to get rid of them so that they are not affected.. Therefore, you need to call setsid () to make the sub-process a new session leader. The sample code is as follows:
setsid();

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. You can create a sub-process again by using the following code:
If (pid = fork () {// parent process exit (0); // ends the first child process and the second child process continues (the second child process is no longer the session leader )}

5) Disable open 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:
// NOFILE is <sys/param. h> macro definition // NOFILE is the maximum number of file descriptors. Different systems have different limits for (I = 0; I <NOFILE; ++ I) {// close the opened file descriptor close (I );}

6) Change 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. The sample code is as follows:
chdir("/");

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 permissions of the files created by the daemon. To prevent this, clear the file creation mask:
umask(0);

8) Process SIGCHLD Signal
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 (zombie), occupying system resources (for more details about the zombie process, please refer to "zombie process of special processes"). 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.

The sample code is as follows:
# Include <unistd. h> # include <signal. h> # include <fcntl. h> # include <sys/syslog. h> # include <sys/param. h> # include <sys/types. h> # include <sys/stat. h> # include <stdio. h> # include <stdlib. h> # include <time. h> int init_daemon (void) {int pid; int I; // 1) shield some signal (SIGTTOU, SIG_IGN) Controlling terminal operations; signal (SIGTTIN, SIG_IGN ); signal (SIGTSTP, SIG_IGN); signal (SIGHUP, SIG_IGN); // 2) run if (pid = fork () {// parent process exit (0) in the background ); // end the parent process, child process continues} else if (pid <0) {// error perror ("fork"); exit (EXIT_FAILURE);}/3) exit Control terminal, logon session, and process group setsid (); // 4) prohibit the process from re-opening the control terminal if (pid = fork ()) {// parent process exit (0); // end the first child process, and the second child process continues (the second child process is no longer the session leader)} else if (pid <0) {// error perror ("fork"); exit (EXIT_FAILURE);} // 5) Close the opened file descriptor // NOFILE is <sys/param. h> macro definition // NOFILE is the maximum number of file descriptors. Different systems have different limits for (I = 0; I <NOFILE; ++ I) {close (I );} // 6) change the current working directory chdir ("/tmp"); // 7) reset the file to create the mask umask (0); // 8) process SIGCHLD signal (SIGCHLD, SIG_IGN); return 0 ;}int main (int argc, char * argv []) {init_daemon (); while (1); return 0 ;}

The running result is as follows:

For sample code downloading in this tutorial, click here.
References: Linux Advanced Programming

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.