What is a daemon.
A daemon is a program or script that runs in an “astral plane”. It is not attached to a terminal nor to a regular job session. Its existence goes beyond a normal process job.
Run in the background
The process must not depend on an interactive terminal.
Perform a fork() and terminate the parent process
This allows the daemon to continue running independently of the process that started it.
Create a new session with setsid()
This ensures that the process:
- Has no controlling terminal
- Becomes the leader of a new session.
Change the working directory (normally to /)
This prevents the daemon from locking directories that might later need to be unmounted.
Reset the file creation mask with umask(0)
This prevents inheriting unexpected permission restrictions from the parent process.
Close the standard file descriptors
Close:
- stdin
- stdout
- stderr
Use a logging system instead of printing to the terminal
Normally using syslog.
Maintain a continuous execution loop
Usually a loop that performs periodic tasks.
Example of a Daemon in C.
This example was taken from the video of the reference with authorship by Last Dragon.
Purpose of the daemon.
The purpose of this daemon is to mount an HDD and prevent it from being unmounted. When the system restarts or shuts down the daemon will unmount the device so the shutdown process can complete without problems.
Code.
|
|