You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.5 KiB

  1. #include <iostream>
  2. #include <event2/event.h>
  3. #include <string.h>
  4. #include <thread>
  5. #ifdef _WIN32
  6. #else
  7. #include <signal.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <fcntl.h>
  12. #endif // !_WIN32
  13. using namespace std;
  14. void read_file(evutil_socket_t fd,short event,void *arg){
  15. char buf[1024] = {0};
  16. int len = read(fd,buf,sizeof(buf) - 1);
  17. if(len > 0){
  18. cout << buf << endl; // 当有用户登录就会把 该信息打印出来
  19. }else {
  20. cout << "." << endl;
  21. this_thread::sleep_for(500ms);
  22. }
  23. }
  24. int main(int agrc,char** agrv){
  25. #ifdef _WIN32
  26. //初始化socket库
  27. WSADATA wsa;
  28. WSAStartup(MAKEWORD(2, 2), &wsa);
  29. #else
  30. if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { //忽略管道信号,发送数据给已关闭的socket,会飞掉!
  31. return 1;
  32. }
  33. #endif
  34. event_config* conf = event_config_new();
  35. event_config_require_features(conf,EV_FEATURE_FDS);
  36. event_base *base = event_base_new_with_config(conf);
  37. event_config_free(conf);
  38. if(!base){
  39. cerr << "event_base_new_with_config failed" <<endl;
  40. }
  41. int sock = open("/var/log/auth.log",O_RDONLY|O_NONBLOCK,0);
  42. if(sock < 0){
  43. cerr << "/var/log/auth.log open failde" << endl;
  44. }
  45. lseek(sock,0,SEEK_END);
  46. //监听文件数据
  47. event* fev = event_new(base,sock,EV_READ|EV_PERSIST ,read_file,0);
  48. event_add(fev,NULL);
  49. //进入事件主循环
  50. event_base_dispatch(base);
  51. event_free(fev);
  52. event_base_free(base);
  53. return 0;
  54. }