목. 8월 7th, 2025

What is a Daemon?

A daemon is a background process that runs independently of user sessions, performing tasks like handling network requests or system maintenance. Unlike regular programs, daemons have no controlling terminal and operate “detached” from direct user interaction.

Step-by-Step Implementation

Here’s how to create a basic daemon in C on Linux:

1. Fork and Exit the Parent

pid_t pid = fork();  

if (pid  0) exit(EXIT_SUCCESS); // Parent exits  

Why? The parent exits immediately, making the child an orphan adopted by init (PID 1). This detaches the process from the original shell.

2. Create a New Session

if (setsid() = 0; x--) {  
    close(x);  
}  

Why? Releases resources and avoids conflicts with open descriptors.

6. Redirect Standard I/O (Optional)

open("/dev/null", O_RDWR); // stdin  
dup(0); // stdout  
dup(0); // stderr  

Why? Prevents accidental I/O operations. Redirects stdin/stdout/stderr to /dev/null or log files.

Full Example Code

#include   
#include   
#include   
#include   

int main() {  
    pid_t pid = fork();  
    if (pid  0) exit(EXIT_SUCCESS);  

    setsid();  
    chdir("/");  
    umask(0);  

    // Close all open descriptors  
    for (int x = sysconf(_SC_OPEN_MAX); x >= 0; x--) close(x);  

    // Redirect standard streams  
    open("/dev/null", O_RDWR); // stdin  
    dup(0); // stdout  
    dup(0); // stderr  

    // Daemon logic here (e.g., infinite loop)  
    while (1) {  
        /* Perform tasks */  
        sleep(60);  
    }  
    return EXIT_SUCCESS;  
}  

Modern Alternatives

  1. daemon() Function
    Simplify with this glibc function:

    daemon(0, 0); // Fork, setsid, chdir, close descriptors  

    Caution: Not POSIX-standard and varies across systems.

  2. Supervisors (e.g., systemd)
    Use systemd to manage daemons:

    • Create a .service file (e.g., /etc/systemd/system/mydaemon.service)
    • Define [Service] with ExecStart, Restart, and User directives.

Key Considerations

  • Logging: Use syslog instead of printf for system-wide logging.
  • Security: Run as unprivileged users where possible.
  • Signals: Handle SIGTERM/SIGHUP for graceful shutdown/reconfiguration.
  • PID Files: Write the daemon’s PID to /var/run/ for tracking.

Conclusion

While creating raw daemons teaches core Linux concepts, consider production-ready tools like systemd for process supervision, logging, and security. For most modern systems, writing a systemd service is the recommended approach.

> Pro Tip: Test daemons with ps aux | grep your_daemon and monitor logs in /var/log/syslog.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다