#include <iostream>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <event2/event.h>
using namespace std;
static void READ_CB(int sock, short which , void* arg)
{
char szBuff[1024];
memset(szBuff, 0, sizeof(szBuff));
int rd_len = read(sock, szBuff, sizeof(szBuff)-1);
if (rd_len > 0)
{
cout<<szBuff<<endl;
}
}
int main()
{
//初始化配置上下文
event_config *pevconf = event_config_new();
if (!pevconf)
{
cerr<<"event_config_new error"<<endl;
return -1;
}
//EV_FEATURE_FDS:需要一个允许文件描述符和套接字的事件方法
event_config_require_features(pevconf, EV_FEATURE_FDS);
event_base *pevbs = event_base_new_with_config(pevconf);
if (!pevbs)
{
cerr<<"event_base_new_with_config error"<<endl;
return -1;
}
//以非阻塞性读取打开系统文件
int sock = open("/var/log/auth.log", O_RDONLY | O_NONBLOCK, 0);
//将sock文件移动到文件末尾,否则会从文件开头开始读取
lseek(sock, 0, SEEK_END);
//文件读取、持久性事件
event* pevf = event_new(pevbs, sock, EV_READ|EV_PERSIST, READ_CB, event_self_cbarg());
if (!pevf)
{
cerr<<"event_new error"<<endl;
}
event_add(pevf, NULL);
event_base_dispatch(pevbs);
event_config_free(pevconf);
event_base_free(pevbs);
return 0;
}
可以进行linux终端登陆来进行测试
./event_file
Feb 5 01:29:31 ubuntu1 sshd[17635]: Accepted password for zhangsan from 192.168.202.1 port 52975 ssh2
Feb 5 01:29:31 ubuntu1 sshd[17635]: pam_unix(sshd:session): session opened for user zhangsan by (uid=0)
Feb 5 01:29:31 ubuntu1 systemd-logind[910]: New session 506 of user zhangsan.
Feb 5 01:31:09 ubuntu1 sshd[17635]: pam_unix(sshd:session): session closed for user zhangsan
Feb 5 01:31:09 ubuntu1 systemd-logind[910]: Removed session 506.