Create Linux Daemon: Step-by-Step Guide
To create a daemon in a Linux system, you can follow these steps.
Creating a child process and then exiting the parent process ensures that the child process is not a process group leader, allowing it to create a new session using the setsid() function.
pid_t pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
Setting the file permissions mask (umask) can ensure that the files created by the daemon process have the appropriate permissions.
umask(0);
Switch the working directory to the root directory. This ensures that the daemon does not occupy any mounted file systems.
chdir("/");
Close the file descriptors to release any unnecessary file descriptors inherited from the parent process by the daemon.
int fd;
for (fd = sysconf(_SC_OPEN_MAX); fd > 0; fd--) {
close(fd);
}
Redirect standard input, standard output, and standard error output to /dev/null. This ensures that any attempts to read from or write to standard input or output will not affect the daemon.
open("/dev/null", O_RDONLY); // 标准输入
open("/dev/null", O_RDWR); // 标准输出
open("/dev/null", O_RDWR); // 标准错误输出
6. Implementing the core logic of the daemon process.
// 守护进程核心逻辑
This creates a simple daemon process. You can put the above code into a function and then call that function at the program’s entry point.