[R&D Notes] Implementing Linux Daemons in Embedded Systems

Implementing Daemons in Embedded Linux systems is a fundamental task for long-running services. Based on the excellent Linux Daemon Writing HOWTO by Devin Watson, I have refactored several processes in my current project to run as background services (daemons).

By backgrounding these processes, we ensure they remain resident in the system without blocking the console or being tied to a specific session.

Core Implementation Pattern

The following C snippet demonstrates the standard procedure for “daemonizing” a process: fork() from the parent, create a new session with setsid(), change the working directory, and close standard file descriptors.

int main(void) {
    pid_t pid, sid;

    // 1. Fork off the parent process
    pid = fork();
    if (pid < 0) exit(EXIT_FAILURE);
    if (pid > 0) exit(EXIT_SUCCESS); // Exit parent

    // 2. Change the file mode mask
    umask(0);

    // 3. Create a new SID for the child process
    sid = setsid();
    if (sid < 0) exit(EXIT_FAILURE);
      
    // 4. Change the working directory to root
    if ((chdir("/")) < 0) exit(EXIT_FAILURE);
      
    // 5. Close out the standard file descriptors
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    // Daemon-specific initialization
    // For example, initializing GPIO pins
    system("/usr/sbin/setgpio -il");

    while(1) {
        // Main service loop
        char message[20];
        // Custom helper to capture command output
        my_system("/usr/sbin/getgpio --status", message, 20);
        
        if(message[17]=='0') {
            system("/usr/sbin/setgpio -ol");
        } else if(message[17]=='1') {
            system("/usr/sbin/setgpio -oh");
        }

        sleep(5); // Polling interval
    }
    return 0;
}

This structural approach provides a clean and reliable way to manage background hardware monitoring or control tasks in resource-constrained embedded environments.


Comments & Feedback