libevent 读取用户登陆日志文件并监听文件更新


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <event2/event_struct.h>
#include <fcntl.h>
#include <event.h>
#include <event2/listener.h>
#include <event2/bufferevent_struct.h>
#include <event2/event-config.h>
#include <event2/event.h>
//var/log/auth.log 监听日志

void callback(int fd,short which,void *arg)
{
    
    
    char buf[1024]={0};
    int len =read (fd,buf,sizeof(buf)-1);
    if(len>0)
    {
        printf("%s",buf);
    }
}
int main(int argc,char *argv[])
{


    int i=0;
    int feature;
    struct event_config *evconfig=event_config_new();
    //设置支持文件描述符
    event_config_require_features(evconfig,EV_FEATURE_FDS);
    
    struct event_base *base=event_base_new_with_config(evconfig);
    event_config_free(evconfig);//释放配置
    
    if(!base)
    {
        perror("event base error");
        exit(1);
    }
    // 确认特征是否生效
    feature=event_base_get_features(base);
    if(feature&EV_FEATURE_ET)     // 边沿触发,高效但是容易丢消息,注意与水平触发区分
    {
        printf("EV_FEATURE_ET support\n");
    }else    printf("EV_FEATURE_ET not support\n");

    // 要求具有很多事件的后台方法可以以近似O(1)处理事件;select和poll
    // 无法提供这种特征,它们只能提供近似O(N)的操作
    if(feature&EV_FEATURE_O1)
    {
        printf("EV_FEATURE_O1 support\n");
    }else    printf("EV_FEATURE_O1 not support\n");

    // 后台方法可以处理包括sockets在内的各种文件描述符
    if(feature&EV_FEATURE_FDS)
    {
        printf("EV_FEATURE_FDS support\n");
    }else    printf("EV_FEATURE_FDS not support\n");

    // 要求后台方法可以使用EV_CLOSED检测链接关闭,而不需要读完所有未决数据才能判断
    // 支持EV_CLOSED的后台方法不是所有OS内核都支持的
    if(feature&EV_FEATURE_EARLY_CLOSE)
    {
        printf("EV_FEATURE_EARLY_CLOSE support\n");
    }else    printf("EV_FEATURE_EARLY_CLOSE not support\n");
    
    //显示支持的网络模式
    const char **methods=event_get_supported_methods();
    for(i=0;methods[i]!=NULL;i++)
    {
        printf("%s\n",methods[i]);

    }
    //打开文件只读非阻塞
    int sock=open("/var/log/auth.log",O_RDONLY);
    if(sock<=0)
    {
        perror("open file error");
        exit(1);
    }
    lseek(sock,0,SEEK_END);
    struct event *fev=event_new(base ,sock,EV_READ|EV_PERSIST,callback,event_self_cbarg());
    event_add(fev,NULL);
    
    // 获取当前网络模型
    printf("current net methods:%s\n",    event_base_get_method(base));
   
	event_base_dispatch(base);
    event_base_free(base);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值