问题描述
我一直在寻找,我在Linux中遇到了 timerfd_create
和 epoll
函数。在一个教程中,有人说 epoll_ctl()
具有 epoll_data_t
的 epoll_event联合成员
结构,可用于在 timerfd
事件触发时执行回调
函数。但是我不确定该怎么做。有人可以帮忙吗?
I have been searching an answer for this question and I came across the functions timerfd_create
and epoll
in Linux. In a tutorial it was said that epoll_ctl()
has an epoll_data_t
union member of the epoll_event
structure which can be used to execute a callback
function on a timerfd
event firing. But I am not sure on how to do it. Can anyone please help.
推荐答案
您不能将回调函数指针放入 epoll_event
,因为它不适合以下任何插槽:
You can't put a callback function pointer into epoll_event
because it can't fit in any of these slots:
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
您可以做的是将计时器fd存储在 epoll_event
并检查是否触发该事件:
What you could do instead is store the timer fd in the epoll_event
and check to see if that's the one that fires:
epoll_event ev;
ev.data.fd = timerfd;
epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev);
使用该设置,然后我们调用 epoll_wait
,我们可以检查触发的事件
是否用于 timerfd
:
With that setup, then when we call epoll_wait
, we can check to see if the event
that fired was for timerfd
:
int n = epoll_wait (epollfd, events , num_events, -1 );
for (int i = 0; i < n; ++i) {
if (events[i].data.fd == timerfd) {
handle_timer_callback();
}
else {
// something else
}
}
或者,如果您愿意放弃一些性能,则可以为事件创建完整的对象层次结构:
Alternatively, if you're open to giving up some performance, you can just create a complete object hierarchy for events:
class EventHandler {
public:
virtual ~EventHandler() = default;
virtual int fd() const = 0;
virtual void fire() = 0;
};
您可以将 EventHandler *
存储到 ptr
:
EventHandler* handler = new TimerHandler();
ev.data.ptr = handler;
epoll_ctl(epollfd, EPOLL_CTL_ADD, handler->fd(), &ev);
这样,如果一切我们放入 epoll
是 EventHandler
:
And that way, if everything we put into epoll
is an EventHandler
:
int n = epoll_wait (epollfd, events , num_events, -1 );
for (int i = 0; i < n; ++i) {
static_cast<EventHandler*>(events[i].data.ptr)->fire();
}
这篇关于如何在C ++中将回调函数指针传递给epoll_event结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!