Skip to content

Instantly share code, notes, and snippets.

@mmozeiko mmozeiko/eventd_example.c Secret
Created Apr 19, 2018

Embed
What would you like to do?
how to use eventfd
#include <stdint.h>
#include <sys/eventfd.h>
#include <sys/select.h>
#include <sys/epoll.h>
#include <unistd.h>
typedef int Event;
static Event CreateEvent(int signaled)
{
return eventfd(signaled ? 1 : 0, EFD_CLOEXEC);
}
static void CloseEvent(Event ev)
{
close(ev);
}
static void SignalEvent(Event ev)
{
uint64_t value = 1;
write(ev, &value, sizeof(value));
}
// returns -1 for timeout
static int WaitEvent(Event ev, int timeout_msec /* -1 if infinite */)
{
if (timeout_msec < 0)
{
uint64_t value;
read(ev, &value, sizeof(value));
return 0;
}
else
{
fd_set f;
FD_ZERO(&f);
FD_SET(ev, &f);
struct timeval t = { 0, timeout_msec * 1000 };
if (select(1, &f, NULL, NULL, &t) == 0)
{
return -1;
}
else
{
return 0;
}
}
}
// returns -1 for timout or index
static int WaitEvents(int count, Event* ev, int waitAll, int timeout_msec /* -1 if infinite */)
{
int e = epoll_create(count);
assert(e!=0);
struct epoll_event event[64]; // assume count <= 64
for (int i=0; i<count; i++)
{
event[i].events = EPOLLIN;
event[i].data.u32 = i;
int x = epoll_ctl(e, EPOLL_CTL_ADD, ev[i], event + i);
assert(x==0);
}
// do the wait
int result = -1;
int waiting = waitAll ? count : 1;
struct epoll_event revent[64]; // assume count <= 64
while (waiting > 0)
{
int ret = epoll_wait(e, revent, waiting, timeout_msec);
if (ret == 0)
{
if (waitAll)
{
result = -1;
}
break;
}
for (int i=0; i<ret; i++)
{
epoll_ctl(e, EPOLL_CTL_DEL, ev[revent[i].data.u32], NULL);
}
result = revent[0].data.u32;
waiting -= ret;
}
close(e);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.