Ordinary Daemon
This is a simple UNIX daemon implemented in C that logs uptime and signal statistics to both a file and syslog.
Features
- Runs as a background daemon process.
- Handles the following signals:
- SIGUSR1 — increments an internal counter and triggers logging.
- SIGALRM — triggers logging and re-arms itself every 300 seconds.
- Logs:
- Time elapsed since the daemon started.
- PID of the daemon process.
- Number of
SIGUSR1
signals received. - Writes logs to:
/tmp/ordinary_daemon.log
(text file)- System log (via
syslog
with facilityLOG_USER
). - Detaches from the terminal, redirects standard streams to
/dev/null
. - Double-fork daemonization to ensure it is fully detached from the controlling terminal.
How It Works
- On startup, the process daemonizes itself:
- Closes standard file descriptors.
- Changes working directory to
/
. - Creates a new session (
setsid()
). - Forks twice to prevent acquiring a controlling terminal.
- Opens
/tmp/ordinary_daemon.log
for writing. - Sets up signal handlers for
SIGUSR1
andSIGALRM
. - Starts a 300-second alarm to trigger periodic logging.
- Waits in an infinite loop (
pause()
), writing logs when a signal is received.
Usage
Compile:
git clone https://git.scratko.xyz/typical-daemon-process
cd typical-daemon-process
gcc -o ordinary_daemon daemon.c
Run:
./ordinary_daemon
Send signals:
kill -USR1 <pid> # increment counter and log immediately
kill -ALRM <pid> # log immediately and restart 300s timer
View log file:
cat /tmp/ordinary_daemon.log
View syslog output (example for systemd-based systems):
journalctl -t "ordinary daemon"
Example Log Entry
time spent (in sec): 120.50 pid: 12345 SIGUSR1: 3