例子3:
libev实现捕获SIGINT信号
写一个类,使用类的成员函数捕获这个异步事件,并打印当前系统时间。
这个类统计捕获SIGINT信号的次数。
3.1使用全局函数处理。
main.cpp
#include <ev++.h>
#include <stdio.h>
#include <sys/time.h>
#include "usertime.h"
void SignalCb(struct ev_loop *loop, struct ev_signal *w, int revents);
int main()
{
ev::default_loop Loop;
ev::sig SigEv(Loop);
SigEv.set_(NULL, SignalCb);
SigEv.start(SIGINT);
TIME_TYPE NowTime;
UserTime::GetSysTime(&NowTime);
Loop.run();
return 0;
}
void SignalCb(struct ev_loop *loop, struct ev_signal *w, int revents)
{
static int count = 0;
count++;
printf("\n信号发送了%d次\n\n", count);
TIME_TYPE NowTime;
UserTime::GetSysTime(&NowTime);
}
usertime.cpp
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include "usertime.h"
int UserTime::GetSysTime(TIME_TYPE *atime)
{
time_t rawtime;
struct tm* tm_type;
struct timeval ttime;
time (&rawtime);
tm_type = localtime (&rawtime);
gettimeofday(&ttime, NULL);
printf("当前时间为:%04d-%02d-%02d %02d:%02d:%02d:%d\n",
tm_type->tm_year+1900, tm_type->tm_mon+1, tm_type->tm_mday,
tm_type->tm_hour, tm_type->tm_min, tm_type->tm_sec,
(ttime.tv_usec/1000));
return 0;
}
usertime.h
#ifndef TIME_H__
#define TIME_H__
typedef struct
{
int year;
int mon;
int day;
int hour;
int min;
int sec;
int millsec;
} TIME_TYPE;
// 打印时间类
class UserTime
{
public:
UserTime()
{
};
~UserTime()
{
};
static int GetSysTime(TIME_TYPE *tm_type);
};
#endif