Created
May 10, 2014 11:28
-
-
Save mdijoux/4c59805bcef4dec9ca36 to your computer and use it in GitHub Desktop.
A linux daemon template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <errno.h> | |
#include <unistd.h> | |
#include <syslog.h> | |
#include <string.h> | |
int main(void) { | |
/* Our process ID and Session ID */ | |
pid_t pid, sid; | |
/* Fork off the parent process */ | |
pid = fork(); | |
if (pid < 0) { | |
exit(EXIT_FAILURE); | |
} | |
/* If we got a good PID, then | |
we can exit the parent process. */ | |
if (pid > 0) { | |
exit(EXIT_SUCCESS); | |
} | |
/* Change the file mode mask */ | |
umask(0); | |
/* Open any logs here */ | |
/* Create a new SID for the child process */ | |
sid = setsid(); | |
if (sid < 0) { | |
/* Log the failure */ | |
exit(EXIT_FAILURE); | |
} | |
/* Change the current working directory */ | |
if ((chdir("/")) < 0) { | |
/* Log the failure */ | |
exit(EXIT_FAILURE); | |
} | |
/* Close out the standard file descriptors */ | |
close(STDIN_FILENO); | |
close(STDOUT_FILENO); | |
close(STDERR_FILENO); | |
/* Daemon-specific initialization goes here */ | |
//Look for config file (else default) | |
/* The Big Loop */ | |
while (1) { | |
//Look for task | |
/* Launch tasks when needed */ | |
sleep(300); /* wait 5 minutes (5* 60 seconds) */ | |
} | |
exit(EXIT_SUCCESS); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment