In Linux, a daemon is a program that runs in the background, often initiated at system boot and not associated with any terminal device. Creating a daemon involves the following steps:
- Create a child process and terminate the parent process: This is the standard method for enabling background execution. Use
fork()to create a child process, then have the parent process exit viaexit(). This ensures the daemon is not the leader of the process group after startup, allowing it to operate independently from the controlling terminal.
Example code:
cpid_t pid = fork(); if (pid < 0) { perror("fork failed"); exit(EXIT_FAILURE); } if (pid > 0) { // Parent process exits directly exit(EXIT_SUCCESS); }
- Change the file mode mask (umask): Set new file permissions to ensure file permissions remain unaffected even if the daemon inherits an incorrect umask value when creating files.
Example code:
cumask(0);
- Create a new session and process group: By calling
setsid(), the process becomes the session leader and process group leader, detaching from the original controlling terminal.
Example code:
cpid_t sid = setsid(); if (sid < 0) { perror("setsid failed"); exit(EXIT_FAILURE); }
- Change the current working directory: Daemons typically change their working directory to the root directory (
/), preventing them from locking other filesystems and making them unmountable.
Example code:
cif ((chdir("/")) < 0) { perror("chdir failed"); exit(EXIT_FAILURE); }
- Close file descriptors: Daemons typically do not use standard input, output, or error file descriptors (stdin, stdout, stderr). Closing these unnecessary file descriptors prevents the daemon from inadvertently using terminals.
Example code:
cclose(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO);
-
Handle signals: Daemons should properly handle received signals, such as SIGTERM. This usually involves writing signal handlers to ensure graceful termination.
-
Execute the daemon's task: After completing the above steps, the daemon enters its main loop to perform core tasks.
By following these steps, you can create a basic daemon. Depending on specific requirements, additional configurations may be needed, such as using log files to record status or handling more signal types.
2024年7月5日 10:36 回复