linux中使用守护进程实现新进程重启

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值