繁体   English   中英

libevent-event_base_loop()是否应该重复获取事件?

[英]libevent - event_base_loop() should it get events repeatly?

这是一个在Linux上使用libevent的简单程序,它跟踪stdout fd,当可写时,回调会将一些信息打印到stdout


hello_libevent.c:

// libevent hello
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include <event2/event.h>
#include <event2/thread.h>


void event_callback(evutil_socket_t fd, short events, void *arg) {
    if(events | EV_WRITE) {
        write(fd, "hello\n", 7);
    }

    sleep(1);
}

int libevent_test() {
    int opr;

    // enable pthread
    if(evthread_use_pthreads() == -1) {
        printf("error while evthread_use_pthreads(): %s\n", strerror(errno));
        return -1;
    }

    // create event_base
    struct event_base* eb;
    if((eb = event_base_new()) == NULL) {
        printf("error while event_base_new(): %s\n", strerror(errno));
        return -1;
    }

    // create event
    int fd_stdout = fileno(stdout);
    struct event* event_stdout;
    event_stdout = event_new(eb, fd_stdout, EV_WRITE, &event_callback, NULL);

    // add event as pending
    struct timeval timeout = {10, 0};
    if(event_add(event_stdout, &timeout) == -1) {
        printf("error while event_add(): %s\n", strerror(errno));
        return -1;
    }

    // dispatch
    if((opr = event_base_loop(eb, EVLOOP_NONBLOCK)) == -1) {
        printf("error while event_base_dispatch(): %s\n", strerror(errno));
        return -1;
    } else if(opr == 1) {
        printf("no more events\n");
    } else {
        printf("exit normally\n");
    }

    // free event
    event_free(event_stdout);

    return 0;
}

int main(int argc, char * argv[]) {
    return libevent_test();
}

编译:

gcc -Wall hello_libevent.c -levent -levent_pthreads

执行结果:

hello
no more events

问题:

  • 在测试中,事件仅发生一次,这是预期的行为吗? 还是应该循环获取更多事件直到超时?
  • 如何使其连续获得事件? 在已经是loop ,是否有必要在循环中调用event_base_loop

http://www.wangafu.net/~nickm/libevent-book/Ref3_eventloop.html看来,您可以在循环内调用event_base_loopevent_base_dispatch

while (1) { /* This schedules an exit ten seconds from now. */ event_base_loopexit(base, &ten_sec);`` event_base_dispatch(base); puts("Tick"); }

事件的主要目的是通知繁忙的线程有关其他地方发生的某些事件。 因此,这看起来合乎逻辑。

我认为event.h文件参考中提到的事件标志EV_PERSIST可能会有所帮助。

持续事件:激活后不会自动删除。

当具有超时的持续事件被激活时,其超时将重置为0。

代替

//...
event_stdout = event_new(eb, fd_stdout, EV_WRITE, &event_callback, NULL);
//...

您可以将此标志传递给event_new

//...
event_stdout = event_new(eb, fd_stdout, EV_WRITE|EV_PERSIST, &event_callback, NULL);
//...

而代码的其他部分则保持不变。 此时,您只需创建并添加一个事件,就无需在循环内调用event_base_loop。 编译后的程序仅保留打印“ hello”的行,直到终止为止。

顺便说一句,我注意到变化

write(fd, "hello\n", 7);

进入

write(fd, "hello\n", 6);

消除每行的开头字符“ \\ 0”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM