2015-12-17 14:09:44 +01:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <signal.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <syslog.h>
|
2015-12-17 21:47:19 +01:00
|
|
|
#include "utils.h"
|
2015-12-17 14:09:44 +01:00
|
|
|
|
2016-08-23 19:38:07 +02:00
|
|
|
void skeleton_daemon() {
|
2015-12-17 14:09:44 +01:00
|
|
|
pid_t pid;
|
|
|
|
|
|
|
|
/* Fork off the parent process */
|
|
|
|
pid = fork();
|
|
|
|
|
|
|
|
/* An error occurred */
|
|
|
|
if (pid < 0)
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
|
|
|
|
/* Success: Let the parent terminate */
|
|
|
|
if (pid > 0)
|
|
|
|
exit(EXIT_SUCCESS);
|
|
|
|
|
|
|
|
/* On success: The child process becomes session leader */
|
|
|
|
if (setsid() < 0)
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
|
|
|
|
/* Catch, ignore and handle signals */
|
2016-08-23 19:38:07 +02:00
|
|
|
// TODO: Implement a working signal handler */
|
2015-12-17 14:09:44 +01:00
|
|
|
signal(SIGCHLD, SIG_IGN);
|
|
|
|
signal(SIGHUP, SIG_IGN);
|
|
|
|
|
|
|
|
/* Fork off for the second time*/
|
|
|
|
pid = fork();
|
|
|
|
|
|
|
|
/* An error occurred */
|
|
|
|
if (pid < 0)
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
|
|
|
|
/* Success: Let the parent terminate */
|
|
|
|
if (pid > 0)
|
|
|
|
exit(EXIT_SUCCESS);
|
|
|
|
|
|
|
|
/* Set new file permissions */
|
|
|
|
umask(0);
|
|
|
|
|
|
|
|
/* Change the working directory to the root directory */
|
|
|
|
/* or another appropriated directory */
|
|
|
|
chdir("/");
|
|
|
|
|
|
|
|
/* Close all open file descriptors */
|
|
|
|
int x;
|
2016-08-23 19:38:07 +02:00
|
|
|
for (x = sysconf(_SC_OPEN_MAX); x > 0; x--) {
|
|
|
|
close(x);
|
2015-12-17 14:09:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/* Open the log file */
|
2016-08-23 19:38:07 +02:00
|
|
|
openlog("firstdaemon", LOG_PID, LOG_DAEMON);
|
2015-12-17 14:09:44 +01:00
|
|
|
}
|