Add daemonize utils

This commit is contained in:
Sebastian Meßmer 2015-10-15 03:39:02 +02:00
parent b402d99fff
commit 498679f6d4
2 changed files with 57 additions and 0 deletions

49
daemon/daemonize.cpp Normal file
View File

@ -0,0 +1,49 @@
#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>
namespace cpputils {
//TODO Test daemonize()
void daemonize() {
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) {
std::cerr << "Failed to get SID for daemon process" << std::endl;
exit(EXIT_FAILURE);
}
// Change the current working directory to a directory that's always existin
if ((chdir("/")) < 0) {
std::cerr << "Failed to change working directory for daemon process" << std::endl;
exit(EXIT_FAILURE);
}
// Close out the standard file descriptors. The daemon can't use them anyhow.
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
};
}

8
daemon/daemonize.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef CPPUTILS_DAEMON_DAEMONIZE_H
#define CPPUTILS_DAEMON_DAEMONIZE_H
namespace cpputils {
void daemonize();
}
#endif