守护进程的定义:
通常说的Daemon进程,是Linux中的后台服务进程。它是一个生存期较长的进程,通常独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。这事百科对此的解释,在游戏服务器里面也有守护进程,特点大概也类似。
游戏守护进程的定义:
游戏服务器里面的守护进程大概完成的职责有这些。1,负责多个进程的启动;2,在进程挂掉的时候负责启动相应的进程;3,可以查询程序运行的情况等等。
游戏守护进程的原理:
设计守护进程为父进程,验证进程,聊天进程,场景进程为子进程。在程序启动的时候,守护进程首先启动,然后根据不同的参数,启动不同的进程(fork),待所有的进程启动完毕,守护进程阻塞(wait),等待知道某一个子进程异常退出。父进程根据获取到的退出进程的id,查询到到退出的进程是验证进程还是聊天进程或者是场景进程,再次启动相应的进程,再次wait,循环....
部分代码分享:
头文件:
class GameDeamon
{
public:
//守护进程类为单例模式,并且鄙视一下那些写个单例模式都要考虑多线程的人
static GameDeamon* instance();
static GameDeamon* _instance;
virtual ~GameDeamon();
//根据启动参数,启动不同的子进程
int analysis_argumen(int argc,char** argv);
//根据不同的type,启动不同的进程
int active_server(const int type);
//父进程阻塞,直到有进程异常退出
int wait_ex();
//根据不同的type,开启不同的资源
int spawn(const int type);
private:
GameDeamon();
//绑定不同的进程id,到不同的进程type
std::map<int,int> _deamon_map;
};
实现文件:
static const int SERVICE_AUTH = 0;
static const int SERVICE_CHAT = 1;
static const int SERVICE_ENGINE = 2;
GameDeamon* GameDeamon::_instance;
GameDeamon* GameDeamon::instance()
{
if(_instance == NULL)
{
_instance = new GameDeamon();
}
return _instance;
}
INT GameDeamon::active_server(const int type)
{
pid_t _pid;
_pid = fork();
if(_pid < 0)
{
//error
}
else if(_pid == 0)
{
//child process
this->spawn(type);
}
else
{
//parent process
sleep(1);
_deamon_map[_pid] = type;
}
return 0;
}
INT GameDeamon::wait_ex()
{
pid_t pid;
int log;
pid = wait(&log);
this->active_server(this->_deamon_map[pid]);
return this->wait_ex();
}
INT GameDeamon::spawn(const int type)
{
if(type == SERVICE_AUTH)
{
//开启相应的资源
}
//.......
return 0;
}
扩展:
添加信号分析程序,以便查询进程的运行状态
欢迎提出宝贵意见!!!