#if defined(POE_OS_FAMILY_WINDOWS)
#define PATHSEPRATOR '\\'
#else
#define PATHSEPRATOR '/'
#endif
inline string getprocessdir()
{
size_t linksize = 256;
char realpath[256] = {0};
string strdir;
#ifndef WIN32
//可执行文件所在目录
if( readlink("/proc/self/exe", realpath, linksize) != -1 )
#else
if (GetModuleFileNameA(NULL, realpath, (DWORD)linksize))
#endif
{
string strpath = realpath;
strdir = strpath.substr(0, strpath.rfind(PATHSEPRATOR));
}
return strdir;
}
void daemonrun(void)
{
#ifndef WIN32
int pid;
if((pid = fork()) > 0)
{
fprintf(stdout, "[parent process]Info: Forked background with PID: [%d]\n", pid);
exit(0);//是父进程,结束父进程
}
else if(pid < 0)
{
perror ("1st Fork failed\n");
exit(1);//fork失败,退出
}
//是第一子进程,后台继续执行
setsid();// 第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if((pid = fork()) > 0)
{
fprintf(stdout, "[1st child process]Info: Forked background with PID: [%d]\n", pid);
exit(0);//是第一子进 程,结束第一子进程
}
else if(pid < 0)
{
perror ("2nd Fork failed\n");
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长
}
chdir(getprocessdir().c_str());//改变工作目录到/
umask(0);//重设文件创建掩模
fclose(stdin);
fclose(stdout);
fclose(stderr);
#endif
return;
}
#define PATHSEPRATOR '\\'
#else
#define PATHSEPRATOR '/'
#endif
inline string getprocessdir()
{
size_t linksize = 256;
char realpath[256] = {0};
string strdir;
#ifndef WIN32
//可执行文件所在目录
if( readlink("/proc/self/exe", realpath, linksize) != -1 )
#else
if (GetModuleFileNameA(NULL, realpath, (DWORD)linksize))
#endif
{
string strpath = realpath;
strdir = strpath.substr(0, strpath.rfind(PATHSEPRATOR));
}
return strdir;
}
void daemonrun(void)
{
#ifndef WIN32
int pid;
if((pid = fork()) > 0)
{
fprintf(stdout, "[parent process]Info: Forked background with PID: [%d]\n", pid);
exit(0);//是父进程,结束父进程
}
else if(pid < 0)
{
perror ("1st Fork failed\n");
exit(1);//fork失败,退出
}
//是第一子进程,后台继续执行
setsid();// 第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if((pid = fork()) > 0)
{
fprintf(stdout, "[1st child process]Info: Forked background with PID: [%d]\n", pid);
exit(0);//是第一子进 程,结束第一子进程
}
else if(pid < 0)
{
perror ("2nd Fork failed\n");
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长
}
chdir(getprocessdir().c_str());//改变工作目录到/
umask(0);//重设文件创建掩模
fclose(stdin);
fclose(stdout);
fclose(stderr);
#endif
return;
}