#include <yangipc/YangIpc.h>
#include <yangutil/sys/YangCTimer.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
//声明一个Timer
YangCTimer* m_5stimer=NULL;
int g_waitState=0;
//声明一个互斥锁
pthread_mutex_t g_lock ;
//声明一个条件锁
pthread_cond_t g_cond ;
//创建ctrl+c的回调函数,设置b_exit为1,signal通知条件锁在wait处继续执行,此处继续执行会退出程序运行。
static int32_t b_exit = 0;
static void ctrl_c_handler(int s){
printf("\ncaught signal %d, exit.\n",s);
b_exit = 1;
pthread_mutex_lock(&g_lock);
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_lock);
}
static int32_t b_reload = 0;
static void reload_handler(int s){
printf("\ncaught signal %d, reload.\n",s);
b_reload = 1;
}
//timer会定时调用这个函数,函数每次会调用checkAlive方法检查ipc的session是否活跃。
void g_yang_main_doTask(int32_t taskId, void *user) {
if (user == NULL) return;
YangIpc *ipc = (YangIpc*) user;
if (taskId == 5) {
ipc->checkAlive(&ipc->session);
}
}
//创建timer定制执行方法。
void yang_initCtimer(YangIpc* ipc){
m_5stimer = (YangCTimer*) calloc(1, sizeof(YangCTimer));
yang_create_timer(m_5stimer, ipc, 5, 5000);
m_5stimer->doTask = g_yang_main_doTask;
yang_timer_start(m_5stimer);
}
//当结束程序时停止timer的执行。
void yang_stopCtimer(){
yang_timer_stop(m_5stimer);
yang_destroy_timer(m_5stimer);
yang_free(m_5stimer);
}
int main(int argc, char* argv[])
{
struct sigaction sigIntHandler;
struct sigaction sigHupHandler;
pthread_mutex_init(&g_lock,NULL);
pthread_cond_init(&g_cond,NULL);
//ctrl + c to exit
sigIntHandler.sa_handler = ctrl_c_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, 0);
//hup to reload
sigHupHandler.sa_handler = reload_handler;
sigemptyset(&sigHupHandler.sa_mask);
sigHupHandler.sa_flags = 0;
sigaction(SIGHUP, &sigHupHandler, 0);
//创建并初始化ipc
YangIpc ipc;
memset(&ipc,0,sizeof(YangIpc));
yang_create_ipc(&ipc);
ipc.init(&ipc.session);
ipc.start(&ipc.session);
//初始化timer定制检测ipc的session是否活跃
yang_initCtimer(&ipc);
while(!b_exit)
{
g_waitState=1;
//在这里等待条件锁,直到用户Ctrl+c退出或其他地方设置b_exit为1
pthread_cond_wait(&g_cond, &g_lock);
g_waitState=0;
if (b_reload) {
//reload
b_reload = 0;
}
}
//退出程序前停止timer
yang_stopCtimer();
//退出程序前销毁ipc
yang_destroy_ipc(&ipc);
return 0;
}
metartc5_jz源码阅读-main.c
于 2023-12-29 22:01:24 首次发布