blob: 3fc8a966515a797c81ee13a935d1a06dfff7322f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
# 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 facility `LOG_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
1. 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.
2. Opens `/tmp/ordinary_daemon.log` for writing.
3. Sets up signal handlers for `SIGUSR1` and `SIGALRM`.
4. Starts a 300-second alarm to trigger periodic logging.
5. Waits in an infinite loop (`pause()`), writing logs when a signal is received.
## Usage
Compile:
```bash
git clone https://git.scratko.xyz/typical-daemon-process
cd typical-daemon-process
gcc -o ordinary_daemon daemon.c
```
Run:
```bash
./ordinary_daemon
```
Send signals:
```bash
kill -USR1 <pid> # increment counter and log immediately
kill -ALRM <pid> # log immediately and restart 300s timer
```
View log file:
```bash
cat /tmp/ordinary_daemon.log
```
View syslog output (example for systemd-based systems):
```bash
journalctl -t "ordinary daemon"
```
## Example Log Entry
time spent (in sec): 120.50 pid: 12345 SIGUSR1: 3
|