0dc3f0b2a9e35d96496bdc89c073d5c8cbadaa8c
[senf.git] / Utils / DaemonTools.cc
1 // $Id$
2 //
3 // Copyright (C) 2006 
4
5 // Definition of non-inline non-template functions
6
7 #include "DaemonTools.hh"
8 //#include "DaemonTools.ih"
9
10 // Custom includes
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <errno.h>
16
17 #include "Exception.hh"
18
19 //#include "DaemonTools.mpp"
20 #define prefix_
21 ///////////////////////////////cc.p////////////////////////////////////////
22
23 prefix_ void satcom::lib::daemonize()
24 {
25     int pid = fork();
26     if (pid < 0)
27         throw satcom::lib::SystemException("fork",errno);
28     if (pid > 0)
29         ::_exit(0);
30     if (::setsid() < 0)
31         throw satcom::lib::SystemException("setsid",errno);
32 }
33
34 prefix_ void satcom::lib::redirect_stdio(std::string const & path)
35 {
36     int fd = ::open(path.c_str(),O_RDWR);
37     if (fd < 0) throw satcom::lib::SystemException("open",errno);
38     if (dup2(fd,0) < 0) throw satcom::lib::SystemException("dup2",errno);
39     if (dup2(fd,1) < 0) throw satcom::lib::SystemException("dup2",errno);
40     if (dup2(fd,2) < 0) throw satcom::lib::SystemException("dup2",errno);
41     if (::close(fd) < 0) throw satcom::lib::SystemException("close",errno);
42 }
43
44 ///////////////////////////////cc.e////////////////////////////////////////
45 #undef prefix_
46 //#include "DaemonTools.mpp"
47
48 \f
49 // Local Variables:
50 // mode: c++
51 // End: