c - 如何将参数传递给使用 libevent 创建的事件函数?

标签 c libevent

我目前正在尝试使用 libevent 每 n 分钟调用一个函数/一个将调用该函数的事件触发器,并建议可以使用 libevent。我可以使用它每隔 n 秒持续调用一次该函数,但无法弄清楚如何将参数传递给它们。

#include <stdio.h>
#include <sys/time.h>
#include <event.h>

void say_hello(int fd, short event, void *arg)
{
  printf("Hello\n");
  // printf("%d", (int *)arg[0])
}

int main(int argc, const char* argv[])
{
  struct event ev;
  struct timeval tv;

  tv.tv_sec = 3;
  tv.tv_usec = 0;

  event_init();
  // event_set(&my_event, 0, EV_PERSIST, my_function, NULL);
  event_set(&ev, 0, EV_PERSIST, say_hello, NULL);
  // evtimer_set(&ev, say_hello, NULL);
  evtimer_add(&ev, &tv);
  event_dispatch();

  return 0;
}

最佳答案

event_set 已弃用,请改用 event_new:

struct event *event_new(
    struct event_base *,
    evutil_socket_t,
    short,
    event_callback_fn,
    void *       
)   

最后一个参数是要传递的参数:

Parameters
    base    the event base to which the event should be attached.
    fd  the file descriptor or signal to be monitored, or -1.
    events  desired events to monitor: bitfield of EV_READ, EV_WRITE, EV_SIGNAL, EV_PERSIST, EV_ET.
    callback    callback function to be invoked when the event occurs
    callback_arg    an argument to be passed to the callback function

要调度event_new()中指定的事件的执行,使用event_add(),他的原型(prototype)是:

int event_add(
    struct event *ev,
    const struct timeval *timeout
)   

关于c - 如何将参数传递给使用 libevent 创建的事件函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57831340/

相关文章:

c - 线程、事件循环和大量的连接和并发

c - 为什么这个简单的 C 程序会在运行时崩溃?

c - OpenGL 颜色在使用照明时不起作用

c++ - 生成 alpha 图片轮廓的算法?

c - 发布多部分文件上传时 libevent 阻塞

javascript - Node.js 中的本地文件的异步文件 IO 方法如何工作?

java - 在 Java 中保存大型静态类型安全字典的优雅方式 - 或者避免代码太大

c - 需要帮助在 C 数组中添加数字

ubuntu - 在 Ubuntu 12.04 上安装 tmux_1.8 时出现 libevent 错误

epoll - libevent 和 epoll,哪个更有效?