2015-10-15 03:39:02 +02:00
|
|
|
#include "daemonize.h"
|
|
|
|
|
|
|
|
#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>
|
|
|
|
#include <iostream>
|
2015-10-17 03:08:56 +02:00
|
|
|
#include "../logging/logging.h"
|
|
|
|
|
|
|
|
using namespace cpputils::logging;
|
2015-10-15 03:39:02 +02:00
|
|
|
|
|
|
|
namespace cpputils {
|
|
|
|
|
|
|
|
//TODO Test daemonize()
|
|
|
|
|
2015-10-17 18:30:07 +02:00
|
|
|
void daemonize() {
|
2015-10-15 03:39:02 +02:00
|
|
|
pid_t pid = fork();
|
|
|
|
if (pid < 0) {
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
if (pid > 0) {
|
|
|
|
//We're the parent process. Exit.
|
|
|
|
exit(EXIT_SUCCESS);
|
|
|
|
}
|
|
|
|
|
|
|
|
// We're the child process.
|
|
|
|
umask(0);
|
|
|
|
|
|
|
|
// Create a new SID for the child process
|
|
|
|
pid_t sid = setsid();
|
|
|
|
if (sid < 0) {
|
2015-10-17 03:08:56 +02:00
|
|
|
LOG(ERROR) << "Failed to get SID for daemon process";
|
2015-10-15 03:39:02 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Change the current working directory to a directory that's always existin
|
|
|
|
if ((chdir("/")) < 0) {
|
2015-10-17 03:08:56 +02:00
|
|
|
LOG(ERROR) << "Failed to change working directory for daemon process";
|
2015-10-15 03:39:02 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
2015-11-03 21:20:15 +01:00
|
|
|
// Close out the standard file descriptors. The process can't use them anyhow.
|
2015-10-15 03:39:02 +02:00
|
|
|
close(STDIN_FILENO);
|
|
|
|
close(STDOUT_FILENO);
|
|
|
|
close(STDERR_FILENO);
|
|
|
|
};
|
|
|
|
}
|