Browse Source

上传文件至 'test_file'

提交监听文件改变事件demo
master
adminPyf 3 years ago
parent
commit
4ce6693435
2 changed files with 70 additions and 0 deletions
  1. +2
    -0
      test_file/makefile
  2. +68
    -0
      test_file/test_file.cpp

+ 2
- 0
test_file/makefile View File

@ -0,0 +1,2 @@
test_file:test_file.cpp
g++ $^ -o $@ -levent

+ 68
- 0
test_file/test_file.cpp View File

@ -0,0 +1,68 @@
#include <iostream>
#include <event2/event.h>
#include <string.h>
#include <thread>
#ifdef _WIN32
#else
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif // !_WIN32
using namespace std;
void read_file(evutil_socket_t fd,short event,void *arg){
char buf[1024] = {0};
int len = read(fd,buf,sizeof(buf) - 1);
if(len > 0){
cout << buf << endl; // 当有用户登录就会把 该信息打印出来
}else {
cout << "." << endl;
this_thread::sleep_for(500ms);
}
}
int main(int agrc,char** agrv){
#ifdef _WIN32
//初始化socket库
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#else
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
return 1;
}
#endif
event_config* conf = event_config_new();
event_config_require_features(conf,EV_FEATURE_FDS);
event_base *base = event_base_new_with_config(conf);
event_config_free(conf);
if(!base){
cerr << "event_base_new_with_config failed" <<endl;
}
int sock = open("/var/log/auth.log",O_RDONLY|O_NONBLOCK,0);
if(sock < 0){
cerr << "/var/log/auth.log open failde" << endl;
}
lseek(sock,0,SEEK_END);
//监听文件数据
event* fev = event_new(base,sock,EV_READ|EV_PERSIST ,read_file,0);
event_add(fev,NULL);
//进入事件主循环
event_base_dispatch(base);
event_free(fev);
event_base_free(base);
return 0;
}

Loading…
Cancel
Save