libev使用

发布时间 2023-04-09 22:36:35作者: 米歪歪

 

1.安装:https://blog.csdn.net/Dancer__Sky/article/details/85156972

2.使动态链接库生效命令:/sbin/ldconfig -v

3.编译命令:gcc -o libevtest2 libevtest2.c -lev

4.测试程序

    1. root@SHPD18F-SP05:~# cat libevtest2.c
      
      #include <stdio.h>
      #include <stdint.h>
      #include <unistd.h>
      #include <string.h>
      #include <time.h>
      #include <ev.h>
       
      #define TIMER_TEST
      //#define EV_IO_TEST
       
      /*获取系统本地时间打印*/
      uint32_t print_timenow()
      {
        time_t now;
        struct tm *tm_now;
        time(&now);
        tm_now = localtime(&now);
        uint32_t times = tm_now->tm_hour * 3600 + tm_now->tm_min * 60 + tm_now->tm_sec;
        printf("[%02d:%02d:%02d]\r\n", tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec);
        return times;
      }
       
       
      #ifdef TIMER_TEST
      /*定时器事件测试*/
      ev_timer timer_watcher;
       
      static void timer_cb (EV_P_ ev_timer *w, int revents)
      {
        printf("timer clock....");
        print_timenow();
        //ev_timer_stop(EV_A_ w);
        //ev_break(EV_A_ EVBREAK_ONE);
      }
       
      int main()
      {
        /*多线程不安全*/
        struct ev_loop *loop = EV_DEFAULT;
        ev_timer_init (&timer_watcher, timer_cb, 3, 1);
        ev_timer_start (loop, &timer_watcher);
        ev_run (loop, 0);
        return 0;
      }
      #endif
       
       
      #ifdef EV_IO_TEST
       
      ev_io stdin_watcher;
       
      static void stdin_cb (struct ev_loop *loop ,struct ev_io *w, int revents)
      {
        void *user_data = ev_userdata(loop);
        int num = *((int *)user_data);
        printf("stdin input......userdata = %d\r\n", num);
        ev_io_stop (loop, w);
        // this causes all nested ev_run's to stop iterating
        ev_break (EV_A_ EVBREAK_ALL);
      }
       
      int main()
      {
        /*创建一个事件循环,多线程安全*/
        struct ev_loop *loop = ev_loop_new(EVBACKEND_EPOLL);
        if (NULL == loop) {
          printf("create loop failed\r\n");
          return 1;
        }
        //传输用户数据
        int user_data = 666;
        ev_set_userdata(loop, &user_data);
        //初始化并开始
        ev_io_init (&stdin_watcher, stdin_cb, STDIN_FILENO, EV_READ);
        ev_io_start (loop, &stdin_watcher);
        //循环检测事件发生处理
        ev_run (loop, 0);
        return 0;
      }
      #endif