icinga2/base/utility.cpp

43 lines
568 B
C++
Raw Normal View History

2012-04-22 16:45:31 +02:00
#include "i2-base.h"
using namespace icinga;
/**
* Daemonize
*
* Detaches from the controlling terminal.
*/
void Utility::Daemonize(void) {
#ifndef _WIN32
pid_t pid;
int fd;
pid = fork();
2012-04-23 08:42:24 +02:00
if (pid < 0)
throw PosixException("fork failed", errno);
2012-04-22 16:45:31 +02:00
if (pid)
exit(0);
fd = open("/dev/null", O_RDWR);
2012-04-23 08:42:24 +02:00
if (fd < 0)
throw PosixException("open failed", errno);
if (fd != 0)
dup2(fd, 0);
if (fd != 1)
dup2(fd, 1);
if (fd != 2)
dup2(fd, 2);
if (fd > 2)
close(fd);
if (setsid() < 0)
throw PosixException("setsid failed", errno);
2012-04-22 16:45:31 +02:00
#endif
}