98 lines
2.3 KiB
C++
98 lines
2.3 KiB
C++
|
|
#include <sys/wait.h> // 包含 wait 函数
|
||
|
|
|
||
|
|
#include <sched.h>
|
||
|
|
#include <stdio.h>
|
||
|
|
#include <unistd.h>
|
||
|
|
#include <sys/prctl.h>
|
||
|
|
#include <map>
|
||
|
|
#include <fcntl.h>
|
||
|
|
|
||
|
|
#include "service.h"
|
||
|
|
|
||
|
|
#define LOCK_FILE "/tmp/dcapp.lock"
|
||
|
|
|
||
|
|
typedef void (*spawn_proc_pt) (void *data);
|
||
|
|
|
||
|
|
static int isProRun(){
|
||
|
|
int fd = open(LOCK_FILE,O_CREAT | O_RDWR,0666);
|
||
|
|
if(fd <0)
|
||
|
|
return 1;
|
||
|
|
struct flock fl;
|
||
|
|
fl.l_type = F_WRLCK; // 写锁
|
||
|
|
fl.l_whence = SEEK_SET;
|
||
|
|
fl.l_start = 0;
|
||
|
|
fl.l_len = 0;
|
||
|
|
if (fcntl(fd, F_SETLK, &fl) == -1) {
|
||
|
|
close(fd);
|
||
|
|
return 1; // 或者可以选择退出程序,因为已经有实例在运行了
|
||
|
|
}
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
//返回类型是pid_t
|
||
|
|
static pid_t spawn_process(spawn_proc_pt proc, void *data,const char *name){
|
||
|
|
|
||
|
|
pid_t pid;
|
||
|
|
//创建进程
|
||
|
|
pid = fork();
|
||
|
|
|
||
|
|
switch(pid){
|
||
|
|
case -1:
|
||
|
|
fprintf(stderr,"fork() failed while spawning \"%s\"\n",name);
|
||
|
|
return -1;
|
||
|
|
case 0:
|
||
|
|
prctl(PR_SET_PDEATHSIG,SIGKILL);
|
||
|
|
proc(data);
|
||
|
|
return 0;
|
||
|
|
default:
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
printf("start %s %ld\n",name,(long int)pid);
|
||
|
|
return pid;
|
||
|
|
}
|
||
|
|
|
||
|
|
static void worker_process_init(){
|
||
|
|
cpu_set_t cpu_affinity;
|
||
|
|
CPU_ZERO(&cpu_affinity);
|
||
|
|
CPU_SET(random() % CPU_SETSIZE,&cpu_affinity);
|
||
|
|
//sched_setaffinity
|
||
|
|
if(sched_setaffinity(0,sizeof(cpu_set_t),&cpu_affinity) == -1){
|
||
|
|
fprintf(stderr,"sched_setaffinity() failed\n");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
static void worker_process(void *data){
|
||
|
|
if(data == NULL){
|
||
|
|
return ;
|
||
|
|
}
|
||
|
|
IService *pService = (IService*) data;
|
||
|
|
prctl(PR_SET_NAME,pService->getServiceName(),0,0,0);
|
||
|
|
//初始化
|
||
|
|
worker_process_init();
|
||
|
|
pService->Init(NULL);
|
||
|
|
//干活
|
||
|
|
pService->Exec();
|
||
|
|
}
|
||
|
|
|
||
|
|
void start_worker_processes(void *pCfg){
|
||
|
|
std::map<std::string, IService*> map = ServiceFactovy::getServiceMap();
|
||
|
|
for (std::map<std::string, IService*>::iterator itor = map.begin(); itor != map.end(); itor++) {
|
||
|
|
spawn_process(worker_process,itor->second, itor->first.c_str());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
int main(int argc,char **argv){
|
||
|
|
|
||
|
|
sigset_t set, oset;
|
||
|
|
sigemptyset(&set);
|
||
|
|
sigaddset(&set, SIGUSR1);
|
||
|
|
sigprocmask(SIG_SETMASK, &set, &oset);
|
||
|
|
|
||
|
|
if(isProRun())
|
||
|
|
exit(0);
|
||
|
|
start_worker_processes(NULL);
|
||
|
|
wait(NULL);
|
||
|
|
}
|
||
|
|
|
||
|
|
|