Create a simple daemon

Source: Internet
Author: User
Tags session id

1. Concept

Daemons, also known as daemon processes, are a special process that runs in the background, out of the control terminal and periodically performing certain tasks or waiting for an event to occur , leaving the terminal to avoid the information displayed on any terminal by the process during execution. And the process will not be terminated by any terminal interrupt information , most servers under Linux are implemented with Daemons. such as the inted and wed servers on the Internet httpd


2. General steps to create a daemon

(1) Call umask Reset file permission mask

File permission mask: refers to the corresponding bit in the file permission to block out. For example, with a file permission mask of 050, it masks the readable and executable permissions of the filegroup owner. Because the child process created by fork inherits the file mask of the parent process, which creates a problem for the child process to use the file, setting the file mask to 0 (that is, without masking any permissions) can enhance the daemon's flexibility


(2) Creating a child process to exit the parent process

In order to get out of the control terminal, the parent process needs to be inferred, and the subsequent work is done by the child process. In Linux, the parent process exits with the child process, which causes the orphan process to be automatically adopted by the 1th process (init) whenever an orphan process is found, so that the original subprocess becomes the child of the INIT process.

(3) Call SetID (void) function to create a new session in a child process


Man 2 setsid See a description of the SETSID function

Setsid–creates a session and sets Theprocess group ID

#include <unistd.h>

pid_t setsid (void);

Setsid () creates a new session if thecalling process is not a process group leader. The calling process is Theleader of the new session, the process group leader of the new process Group,and have no controll ing TTY. The process group ID and session ID of the The callingprocess is set to the PID of the calling process. The calling process would bethe only process in this new process group and the new session.


Process group: A collection of one or more processes, the process group is uniquely marked by the ID of the process group, each process group has a leader process, and the process number of its leader process equals the process group ID, and the process group ID is not affected by the team leader's exit.

SetID function: Used to create a new session and serve as the leader of the conversation group, which has the following three roles

A. Getting the process out of control of the original session

B. Getting the process out of control of the original conversation group

C. Getting the process out of control of the original session terminal


Purpose of using the SetID function

because the first step of creating the daemon calls the fork function to create the child process and then exits the parent process. Because when the fork function is called, the child process copies the session period of the parent process, the process group, the control terminal, and so on, although the parent process exits but the session, the process group, the control terminal does not change , so it is not really independent. The use of the Ssetid function allows the process to be completely independent from the control of other processes.


(4) Change the current directory to the root directory

A child process created with fork inherits the current working directory of the parent process. Because the file system in which the current directory resides cannot be uninstalled while the process is running, it can be cumbersome to use later, so it is common practice to have the root directory as the current working directory of the Daemon


(5) Close file descriptor

The child process created with fork inherits some files that are already open from the parent process. These open files may never be read and written by the daemon, but they consume resources as well. The daemon has lost contact with the owning control terminal after using SetID, so the process of terminal input cannot reach the daemon. So the file descriptor 0,1,2 has lost the value of being present should be closed

(6) Exit handling of daemon process

When the user needs an external stop daemon, the KILL command is usually used to stop the gatekeeper process

  1  #include <stdio.h>                                                                2  #include < signal.h>  3  #include <unistd.h>  4  #include <stdlib.h>   5  #include <fcntl.h>  6  #include <sys/stat.h>  7   8  void creat_daemon (void) {  9 int i;10 int fd0;11 pid_t pid; 12 struct sigaction sa;13 umask (0);//Set file mask to 014     if (Pid=fork () <0) {15         printf ("child dir error\n");16      }17         else {18          exit (0);//19         }20 21 setid (0);// Set up a new session 22 sa.sa_handler=sig_ign;23 sigemptyset (&sa.sa_mask); 24 sa.sa_flags=0;25 if ( Sigaction (sigchld,&sa,null) <0) {//Register child process Exit Ignore signal  26 return;27 }28 if (Pid=fork () <0) {/ /fork again, terminate the parent process to ensure that the child process is not the first session, and that the process is not disturbed by other processes 29 printf ("fork error!\n");30 return;31 }32  Else if (pid!=0) {33 exit (0) 34 }35 36 if (chdir ("/") <0) {//Change working directory to root directory 37 printf (" child dir error\n ");                                                  38  Return;39 }40 cLose (0); 41 fd0=open ("/dev/null", O_RDWR);//close standard input  , standard output, standard error 42 dup2 (fd0,1); 43 dup2 (fd0,2); 44 }45 46 int main () 47 {48 creat_daemon (); 49 while (1) {50 sleep (1); 51  52 }53 54 }55








So the question comes, why does the daemon function fork two times?????

The reasons are as follows:

(1) The first fork is to let the shell think that this command has been terminated, not to be hung on the input side. There is also a service for the setid behind. The caller of the SetID cannot be the process group leader, at which point the parent process is the process group leader

(2) SetID is an important call in the Daemon function, it completes the Daeemon function to do most of the things called after the child process is the conversation group leader, and out of the original terminal control, the future of the terminal how the new process will not be affected by those signals

(3) The purpose of the second fork is to prevent the process from opening a control terminal again. Because the prerequisite for opening a control terminal is that the process must be the conversation group leader. Fork the sub-process again id!=ppid so you can't open a new control terminal



Create a simple daemon

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.