linux中守护进程:实现服务器进程重启
功能实现:
struct tgExeInfo
{
string sPath; //进程路径
string sExeName; //进程名
};
//实现进程重启
void CRoomPlug::CheckProc()
{
list<tgExeInfo> *plist = m_ConfigInfo.GetExeList();
list<tgExeInfo>::iterator iter;
for (iter = plist->begin(); iter != plist->end(); iter++)
{
tgExeInfo Info = *iter;
cout << "test_CheckProc() " << "it->first = " << Info.sExeName << " it->second = " << Info.sPath << endl;
//cout << "/******************************************/ " << endl;
RunProc(Info.sPath, Info.sExeName);
//cout << "/******************************************/ RunProc() end!!!!!!" << endl;
}
//cout << "/==================================================/ " << "plist,size = " << plist->size() << endl;
}
//重启进程
bool CRoomPlug::RunProc(string sFolder, string sProcName)
{
//TODO:实现进程守护
bool Run = exeirun(sProcName.c_str());
char buf[256] = { '\0' };
if (!Run)
{
std::cout << "test_RunProc(): "<< "exename = " << sProcName << " relay to start" << std::endl;
//重启进程
startbackGroundexe(sFolder, sProcName);
bool newRet = exeirun(sProcName.c_str());
if (1)
{
if (newRet)
{
m_ServerInfo.ProcessInfo(sProcName, sFolder, 1);
std::cout << "test_RunProc(): " << "exename = " << sProcName << " start successfully" << std::endl;
}
else
{
m_ServerInfo.ProcessInfo(sProcName, sFolder, 0);
std::cout << "test_RunProc(): " << "exename = " << sProcName << " start failed" << std::endl;
}
}
}
return true;
}
//启动后台进程
int CRoomPlug::startbackGroundexe(string sFolder, string sProcName)
{
cout << "test_startbackGroundexe: " << "path = " << sFolder << " exeName = " << sProcName << endl;
int fd;
if ((fd = open("/dev/console", O_RDWR)) < 0)
{
fd = open("/dev/null", O_RDWR);
}
printf("THIS IS A TEST\n");
dup2(1, fd);
dup2(2, fd);
pid_t childpid = fork();
if (childpid == -1)
{
perror("Failed to fork, logcat not starting");
return 1;
}
if (childpid == 0)
{
setsid();
string pram1 = sFolder + sProcName;
string pram2 = sProcName;
int execReturn = execl(pram1.c_str(), pram2.c_str(), (char*)0);
cout << "test_startbackGroundexe: " << "pram1 = " << pram1.c_str() << " pram2 = " << pram2.c_str() << endl;
}
else
{
close(fd);
return 0;
}
close(fd);
return 0;
}