For anyone working with Linux, the concept of a “Daemon” (or service) is fundamental. Daemons are background processes that operate independently of any active user session. I recently deep-dived into this topic via Devin Watson’s Linux Daemon Writing HOWTO, which provides a fantastic primer and a clear template.
Building on that foundation, I refactored several processes in my current project to run as persistent background services. Below is a code snippet demonstrating the core structural requirements for a Linux daemon:
int main(void) {
char message[20];
pid_t pid, sid;
// 1. Fork off the parent process
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
// 2. Exit the parent process so it looks like the command finished
if(pid > 0) {
exit(EXIT_SUCCESS);
}
// 3. Change the file mode mask
umask(0);
// 4. Create a new SID for the child process to detach from the terminal
sid = setsid();
if(sid < 0) {
exit(EXIT_FAILURE);
}
// 5. Change the working directory to root for safety
if((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}
// 6. Close out standard file descriptors (STDIN, STDOUT, STDERR)
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Daemon-specific initialization
// Example: Initializing GPIO pins via a helper tool
system("/usr/sbin/setgpio -il");
while(1) {
// Main loop logic: Here we poll GPIO status and react
// Using a custom 'my_system' function to capture output into a buffer
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 to throttle CPU usage
sleep(5);
}
return 0;
}
This structural pattern ensures the process is “detached” from the terminal session that started it, allowing it to survive terminal closure and manage system resources (like GPIO pins) silently in the background.
Comments & Feedback