Linux system Programming--the daemon process of special process

Source: Internet
Author: User

What is a daemon process?

The daemon (Daemon process), which is usually called the Daemon process (daemon), is the background service process in Linux. It is a long-lived process, usually independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences.


The daemon is a special orphan process that is out of the terminal and why is it out of the terminal? the reason for leaving the terminal is to prevent the process from being interrupted by information generated by any terminal, and its information during execution is not displayed on any terminal. because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal will be attached to this terminal, this terminal is called the control terminal of these processes, when the control terminal is closed, the corresponding process will automatically shut down .


most Linux servers are implemented with daemons. For example, the Internet server Inetd,web server httpd and so on.


How to view daemon processes

Knocking at Terminal:PS axj

    • A indicates that not only the process of the current user is listed, but also all other users ' processes
    • X indicates that not only the process of controlling the terminal is listed, but also all the processes that have no control terminal
    • J indicates listing information related to job control


You can see some of the features of the Guardian:

    • Daemons are basically started with Superuser (UID 0)
    • No control terminal (TTY for?) )
    • Terminal Process Group ID is-1 (tpgid indicates terminal process group ID)


In general, Daemons can be started in the following ways:

    • Startup scripts are started at system startup, and these boot scripts are usually placed in the/ETC/RC.D directory;
    • Use the inetd super server to start, such as Telnet;
    • The process initiated by Cron and started with Nohup in the terminal is also the daemon.

How do I write a daemon? The following are the basic procedures for writing daemons:1) shielding some control terminal operation Signal
This is to prevent the daemon from interfering with exiting or suspending the control terminal before it is run.
Signal (sigttou,sig_ign); Signal (sigttin,sig_ign); Signal (sigtstp,sig_ign); Signal (SIGHUP, sig_ign);

2) running in the background
This is to avoid suspending the control terminal from putting the daemon into the background. 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 ()) {//Parent process exit (0);     End parent process, child process continue}

3) out of control terminal, login 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 shell 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 so that they are not affected by them. It is therefore necessary to call SETSID () to make the child process a new session leader, with the sample code as follows:
Setsid ();

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.

4) prevent the process from reopening the control terminal
now, the process has become a session leader without terminal, but it can re-apply to open a control terminal . You can prevent a process from reopening the control terminal by making the process no longer a session leader by creating a sub-process again, with the sample code as follows:
if (Pid=fork ()) {//Parent process exit (0);      End first child process, second child process continues (second child process is no longer session leader)}

5) Close 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:
NOFILE <sys/param.h> macro definition//Nofile as the maximum number of file descriptors, different systems have different restrictions for (i=0; i< nofile; ++i) {//Close Open File descriptor close (i);}

6) 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 a dump core, the process that writes the log runs changes the working directory to a specific directory such as/tmp. The sample code is as follows:
ChDir ("/");

7) Reset file creation mask
The process inherits the file creation mask from the parent process that created it. It may modify the access rights of the files created by the daemon. To prevent this, the file creation mask is cleared:
Umask (0);

8) processing SIGCHLD signal
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 (see "Special process Zombie process" For more details on the zombie process). 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.

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) shields some signal signal (sigttou,sig_ign) for control terminal operation; Signal (sigttin,sig_ign); Signal (sigtstp,sig_ign); Signal (SIGHUP, sig_ign); 2) run in the background if (Pid=fork ()) {//Parent process exit (0);//end parent process, child process continues}else if (pid< 0) {//Error perror ("fork"); Exit (Exit_fai LURE);}  3) Out of control terminal, login session and Process group Setsid ();      4) Disable process re-opening control terminal if (Pid=fork ()) {//Parent process exit (0);  Ends the first child process, 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 Open File descriptor//nofile to <sys/param.h> macro definition//Nofile to maximum number of file descriptors, different systems have different restrictions for (i=0; i< nofile; ++i) {Close (i);} 6) Change the current working directory ChDir ("/tmp");  7) Reset File creation mask umask (0); 8) Processing SIGCHLD signal signal (sigchld,sig_ign); return 0; } int main (int argc, char *argv[]) {Init_daemon(); while (1); return 0;} 

The results of the operation are as follows:

For This tutorial sample code download please click here.
Reference: Linux Advanced Programming

Linux system Programming--the daemon process of special process

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.