-
Notifications
You must be signed in to change notification settings - Fork 48
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
WIP: Implement poll as a wrapper of kevent
- Loading branch information
1 parent
0351451
commit 8bc5e09
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
#include<sys/poll.h> | ||
#include<sys/time.h> | ||
#include<sys/event.h> | ||
#include<stdlib.h> | ||
#include<unistd.h> | ||
#include<errno.h> | ||
|
||
int poll(struct pollfd *fds, nfds_t nfds, int timeout) { | ||
int kq; | ||
int ret; | ||
struct kevent *events; | ||
struct timespec timeout_ts; | ||
int nevents = 0; | ||
|
||
if (nfds < 0 || nfds > (unsigned int)sysconf(_SC_OPEN_MAX)) { | ||
errno = EINVAL; | ||
return -1; | ||
} | ||
|
||
if (timeout >= 0) { | ||
timeout_ts.tv_sec = timeout / 1000; | ||
timeout_ts.tv_nsec = (timeout % 1000) * 1000000; | ||
} | ||
else if (timeout < -1) { | ||
errno = EINVAL; | ||
return -1; | ||
} | ||
|
||
kq = kqueue(); | ||
if (kq < 0) | ||
return -1; | ||
|
||
events = malloc(nfds * sizeof(struct kevent)); | ||
if (!events) { | ||
errno = ENOMEM; | ||
ret = -1; | ||
goto close_kq; | ||
} | ||
|
||
for (unsigned int i = 0; i < nfds; i++) { | ||
if (fds[i].events | POLLIN) | ||
EV_SET(&events[nevents++], fds[i].fd, EVFILT_READ, EV_ADD, 0, 0, 0); | ||
if (fds[i].events | POLLOUT) | ||
EV_SET(&events[nevents++], fds[i].fd, EVFILT_WRITE, EV_ADD, 0, 0, 0); | ||
} | ||
|
||
ret = kevent(kq, events, nevents, events, nevents, timeout == -1 ? NULL : &timeout_ts); | ||
if (ret == -1) | ||
goto end; | ||
|
||
/* TODO - populate `revents` in elements of `fds` array */ | ||
|
||
end: | ||
free(events); | ||
close_kq: | ||
close(kq); | ||
return ret; | ||
} |