Detailed explanation and creation of daemon

Source: Internet
Author: User
Daemon

Daemon is a process that runs in the background and is independent of all terminals.
Why is there a process independent of the terminal? First, we do not want the execution information of these processes to be displayed on any terminal for security reasons. Second, we do not want these processes to be interrupted by the interrupt signal generated by the terminal. Finally, although we can convert the program into background execution through &, we sometimes need the program to automatically transfer it to the background for execution. Therefore, we need a daemon process.

Daemon startup

To start a daemon, you can use the following methods:
1. Start the daemon process through the system initialization script during the system. These scripts are usually in the etc/rc. d directory, and the daemon started by these scripts have superuser permissions. Some basic service programs of the system are usually started in this way.
2. Many network service programs are started by the inetd daemon. We will talk about it later. It listens to various network requests, such as telnet and FTP, and starts corresponding server programs (such as telnet server and FTP Server) when requests arrive)
3. The processing program started regularly by cron. These programs are actually a daemon at runtime.
4. The processing program started by.
5. the daemon can also be started from the terminal. Generally, this method is only used to test the daemon process or stop the process due to a specific cause.
6. process started with nohup on the terminal. This method can be used to change all programs into daemon processes.

To write a daemon

1. Fork
You need to fork a child process and shut down the parent process. If the process is started as a shell command on the command line front end, when the parent process is terminated, shell considers the command to have ended. In this way, a process is automatically called a background process. In addition, the child process inherits the Group Identifier from the parent process and has its own process identifier. This ensures that the child process is not the first process of a process group. This is required for the next step of setsid.
2. setsid
The setsid call creates a new process group, and the calling process becomes the first process of the Process Group. In this way, the process is separated from the original terminal and becomes a process independent from the terminal.
3. Ignore the sighup signal and re-Fork
In this way, the process is not the first process in the process group. In some cases, the process may accidentally open the terminal and re-contact the terminal.
4. Change the working directory and clear the file mask.
The main purpose of changing the working directory is to cut off the connection between the Process and the original file system. And ensure that the process can work normally no matter where it starts. The file mask is cleared to eliminate the impact of the process mask on the files it creates.
(File umask: When you first log on to the system, the umask command determines the default mode for creating files. This command is actually the opposite of the CHMOD command. Your system administrator must set a reasonable umask value for you to ensure that the files you create have the desired default permissions, prevent other users from having the write permission on your files .)
5. Close all opened file handles

This is to prevent the child process from inheriting the files opened in the parent process and keeping these files open all the time, resulting in some conflicts.

Create a daemon. c daemon.

#include <stdio.h>#include <unistd.h>#include <signal.h>#include <syslog.h>#include <sys/types.h>#include <fcntl.h>#include <sys/param.h>#include <stdlib.h>void daemon_init(){int i, fd;pid_t pid;int maxfd;//fork ,disconnected with parentif((pid=fork())){exit(0);}else if(pid<0)exit(1);//first child process, disconnected with process team//create a new sessionsetsid();//fork to end first child process, diconnected with console if((pid=fork())){exit(0);}else if(pid<0)exit(1);//change directory, disconnected with source's file systemchdir("/");//remove file umaskumask(0);//close all file descriptionmaxfd = sysconf(_SC_OPEN_MAX);for(i=0; i<maxfd; i++){close(i);}//redirect stardard input, output, errorif((fd=open("/dev/null", O_RDWR))==-1)exit(-1);dup2(fd, STDIN_FILENO);dup2(fd, STDOUT_FILENO);dup2(fd, STDERR_FILENO);close(fd);}int main(void){FILE *fp=NULL;int t=0;//ignore SIGHUP   signal(SIGHUP, SIG_IGN);daemon_init();fp=fopen("/root/tmp.txt", "a");fprintf(fp, "%s\n", "test message");fflush(fp);  while(1){fprintf(fp, "%d\n", t);fflush(fp);sleep(2);t += 2;}fclose(fp);return 0;}

Run

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.