Lunchbox  1.6.0
daemon.h
00001 
00002 /* Copyright (c) 2012, Stefan.Eilemann@epfl.ch
00003  *
00004  * This library is free software; you can redistribute it and/or modify it under
00005  * the terms of the GNU Lesser General Public License version 2.1 as published
00006  * by the Free Software Foundation.
00007  *
00008  * This library is distributed in the hope that it will be useful, but WITHOUT
00009  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00010  * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
00011  * details.
00012  *
00013  * You should have received a copy of the GNU Lesser General Public License
00014  * along with this library; if not, write to the Free Software Foundation, Inc.,
00015  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00016  */
00017 
00018 #ifndef LUNCHBOX_DAEMON_H
00019 #define LUNCHBOX_DAEMON_H
00020 
00021 #include <lunchbox/debug.h>
00022 #ifndef _MSC_VER
00023 #  include <unistd.h>
00024 #endif
00025 
00026 namespace lunchbox
00027 {
00028 
00039 inline bool daemonize()
00040 {
00041 #ifdef _MSC_VER
00042     LBASSERTINFO( false, "Not implemented" );
00043     return false;
00044 #else
00045     const pid_t pid = fork();
00046     if( pid < 0 )
00047     {
00048         LBWARN << "Fork failed: " << sysError << std::endl;
00049         return false;
00050     }
00051 
00052     if( pid > 0 ) // parent
00053         ::exit( EXIT_SUCCESS );
00054 
00055     const pid_t sid = setsid(); // child, create new seesion
00056     if( sid < 0 )
00057     {
00058         LBWARN << "setsid failed: " << sysError << std::endl;
00059         return false;
00060     }
00061 
00062     // Close the standard file
00063     ::close( STDIN_FILENO );
00064     ::close( STDOUT_FILENO );
00065     ::close( STDERR_FILENO );
00066     return true;
00067 #endif
00068 }
00069 }
00070 
00071 #endif //LUNCHBOX_DAEMON_H