2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Daemon process is a background service process in Linux. It is a long-lived process that is usually independent of the control terminal and periodically performs certain tasks or waits for certain events to occur.
chdir()
Function: Prevent the unmountable file system from being occupied and can also be replaced with other paths;#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
void daemonize(void)
{
pid_t pid;
/*
* 成为一个新会话的首进程,失去控制终端
*/
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
} else if (pid != 0) /* parent */
exit(0);
setsid();
/*
* 改变当前工作目录到/目录下.
*/
if (chdir("/") < 0) {
perror("chdir");
exit(1);
}
/* 设置umask为0 */
umask(0);
//重定向0,1,2文件描述符到 /dev/null,因为已经失去控制终端,再操作0,1,2没有意义.
close(0);
open("/dev/null", O_RDWR);
dup2(0, 1);
dup2(0, 2);
}
int main(void) {
daemonize();
while(1);
/* 在此循环中可以实现守护进程的核心工作 */
}
When you run this program, it becomes a daemon process and is no longer associated with the current terminal. You cannot see it with the ps command, but you must run the ps command with the x parameter to see it. You can also see that closing the terminal window or logging off will not affect the operation of the daemon process.
Why should the daemon process be separated from the controlling terminal?
The reason for being separated from the terminal is to prevent the process from being interrupted by any information generated by the terminal, and the information during the execution is not displayed on any terminal. In Linux, each interface for communication between the system and the user is called a terminal, and each process that starts from this terminal will be based on
Attached to this terminal, this terminal is called the control terminal of these processes. When the control terminal is closed, the corresponding processes will be automatically closed. However, many of our applications do not want to exit the process when the shutdown is interrupted, such as databases, Web services, game services, etc. At this time, a daemon process is needed.
This article introduces the concept of daemon, the programming steps of daemon, code implementation, and the role of daemon, helping us understand the operating principles of background programs.