【问题标题】:How to pass arguments to an event function created using libevent?如何将参数传递给使用 libevent 创建的事件函数?
【发布时间】:2019-09-07 06:41:24
【问题描述】:

我目前正在尝试使用 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中的NULL可以用来传递任何地址,然后在say_hello中将其转换回正确的指针类型
  • event_set()?我不熟悉那个名字的 libevent 函数......你是说event_new() 吗?如果是这样,是的,这是callback_arg 参数。我也没有看到event_init()event_dispatch()...
  • @PiotrSkotnicki 我不知道如何或在哪里通过它们。我想不出一种方法来传递任何东西。尝试将其传递给 NULL 但会引发一堆错误。
  • event_set(&amp;ev, 0, EV_PERSIST, say_hello, argv[0]);,然后是printf("%s", (const char *)arg);

标签: c libevent


【解决方案1】:

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(),他的原型是:

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

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2013-05-16
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    相关资源
    最近更新 更多