diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c --- a/Modules/selectmodule.c +++ b/Modules/selectmodule.c @@ -1058,7 +1058,9 @@ typedef struct { PyObject_HEAD - SOCKET epfd; /* epoll control file descriptor */ + SOCKET epfd; /* epoll control file descriptor */ + int maxevents; /* maximum number of epoll events */ + struct epoll_event *evs; /* epoll events buffer */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; @@ -1078,6 +1080,8 @@ if (self->epfd >= 0) { int epfd = self->epfd; self->epfd = -1; + self->maxevents = 0; + self->evs = NULL; Py_BEGIN_ALLOW_THREADS if (close(epfd) < 0) save_errno = errno; @@ -1114,6 +1118,15 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } + + self->maxevents = FD_SETSIZE; + self->evs = PyMem_New(struct epoll_event, self->maxevents); + if (self->evs == NULL) { + Py_DECREF(self); + PyErr_NoMemory(); + return NULL; + } + return (PyObject *)self; } @@ -1140,6 +1153,7 @@ pyepoll_dealloc(pyEpoll_Object *self) { (void)pyepoll_internal_close(self); + PyMem_Free(self->evs); Py_TYPE(self)->tp_free(self); } @@ -1317,10 +1331,9 @@ { double dtimeout = -1.; int timeout; - int maxevents = -1; + int maxevents = self->maxevents; int nfds, i; PyObject *elist = NULL, *etuple = NULL; - struct epoll_event *evs = NULL; static char *kwlist[] = {"timeout", "maxevents", NULL}; if (self->epfd < 0) @@ -1343,25 +1356,25 @@ timeout = (int)(dtimeout * 1000.0); } - if (maxevents == -1) { - maxevents = FD_SETSIZE-1; - } - else if (maxevents < 1) { + if (maxevents < 1) { PyErr_Format(PyExc_ValueError, "maxevents must be greater than 0, got %d", maxevents); return NULL; - } + } else if (maxevents != self->maxevents) { + struct epoll_event *orig_evs = self->evs; - evs = PyMem_New(struct epoll_event, maxevents); - if (evs == NULL) { - Py_DECREF(self); - PyErr_NoMemory(); - return NULL; + PyMem_RESIZE(self->evs, struct epoll_event, maxevents); + if (self->evs == NULL) { + self->evs = orig_evs; + PyErr_NoMemory(); + return NULL; + } + self->maxevents = maxevents; } Py_BEGIN_ALLOW_THREADS - nfds = epoll_wait(self->epfd, evs, maxevents, timeout); + nfds = epoll_wait(self->epfd, self->evs, self->maxevents, timeout); Py_END_ALLOW_THREADS if (nfds < 0) { PyErr_SetFromErrno(PyExc_OSError); @@ -1374,7 +1387,7 @@ } for (i = 0; i < nfds; i++) { - etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); + etuple = Py_BuildValue("iI", self->evs[i].data.fd, self->evs[i].events); if (etuple == NULL) { Py_CLEAR(elist); goto error; @@ -1383,7 +1396,6 @@ } error: - PyMem_Free(evs); return elist; }