2 select - Module containing unix select(2) call.
3 Under Unix, the file descriptors are small integers.
4 Under Win32, select only exists for sockets, and sockets may
5 have any value except INVALID_SOCKET.
6 Under BeOS, we suffer the same dichotomy as Win32; sockets can be anything
9 Copyright (c) 2015, Daryl McDaniel. All rights reserved.<BR>
10 Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>
11 This program and the accompanying materials are licensed and made available under
12 the terms and conditions of the BSD License that accompanies this distribution.
13 The full text of the license may be found at
14 http://opensource.org/licenses/bsd-license.
16 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
17 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
21 #include <structmember.h>
24 /* Perform runtime testing for a broken poll on OSX to make it easier
25 * to use the same binary on multiple releases of the OS.
27 #undef HAVE_BROKEN_POLL
30 /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
31 64 is too small (too many people have bumped into that limit).
33 Users who want even more than the boosted limit should #define
34 FD_SETSIZE higher before this; e.g., via compiler /D switch.
36 #if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
37 #define FD_SETSIZE 512
40 #if defined(HAVE_POLL_H)
42 #elif defined(HAVE_SYS_POLL_H)
47 /* This is missing from unistd.h */
48 extern void bzero(void *, int);
51 #ifdef HAVE_SYS_TYPES_H
52 #include <sys/types.h>
55 #if defined(PYOS_OS2) && !defined(PYCC_GCC)
61 # include <winsock2.h>
65 # include <net/socket.h>
71 static PyObject
*SelectError
;
73 /* list of Python objects and their file descriptor */
75 PyObject
*obj
; /* owned reference */
77 int sentinel
; /* -1 == sentinel */
81 reap_obj(pylist fd2obj
[FD_SETSIZE
+ 1])
84 for (i
= 0; i
< FD_SETSIZE
+ 1 && fd2obj
[i
].sentinel
>= 0; i
++) {
85 Py_CLEAR(fd2obj
[i
].obj
);
87 fd2obj
[0].sentinel
= -1;
91 /* returns -1 and sets the Python exception if an error occurred, otherwise
95 seq2set(PyObject
*seq
, fd_set
*set
, pylist fd2obj
[FD_SETSIZE
+ 1])
100 PyObject
* fast_seq
= NULL
;
103 fd2obj
[0].obj
= (PyObject
*)0; /* set list to zero size */
106 fast_seq
= PySequence_Fast(seq
, "arguments 1-3 must be sequences");
110 for (i
= 0; i
< PySequence_Fast_GET_SIZE(fast_seq
); i
++) {
113 /* any intervening fileno() calls could decr this refcnt */
114 if (!(o
= PySequence_Fast_GET_ITEM(fast_seq
, i
)))
118 v
= PyObject_AsFileDescriptor( o
);
119 if (v
== -1) goto finally
;
121 #if defined(_MSC_VER) && !defined(UEFI_C_SOURCE)
122 max
= 0; /* not used for Win32 */
123 #else /* !_MSC_VER */
124 if (!_PyIsSelectable_fd(v
)) {
125 PyErr_SetString(PyExc_ValueError
,
126 "filedescriptor out of range in select()");
131 #endif /* _MSC_VER */
134 /* add object and its file descriptor to the list */
135 if (index
>= FD_SETSIZE
) {
136 PyErr_SetString(PyExc_ValueError
,
137 "too many file descriptors in select()");
140 fd2obj
[index
].obj
= o
;
141 fd2obj
[index
].fd
= v
;
142 fd2obj
[index
].sentinel
= 0;
143 fd2obj
[++index
].sentinel
= -1;
154 /* returns NULL and sets the Python exception if an error occurred */
156 set2list(fd_set
*set
, pylist fd2obj
[FD_SETSIZE
+ 1])
162 for (j
= 0; fd2obj
[j
].sentinel
>= 0; j
++) {
163 if (FD_ISSET(fd2obj
[j
].fd
, set
))
166 list
= PyList_New(count
);
171 for (j
= 0; fd2obj
[j
].sentinel
>= 0; j
++) {
173 if (FD_ISSET(fd
, set
)) {
175 fd2obj
[j
].obj
= NULL
;
176 /* transfer ownership */
177 if (PyList_SetItem(list
, i
, o
) < 0)
189 #undef SELECT_USES_HEAP
190 #if FD_SETSIZE > 1024
191 #define SELECT_USES_HEAP
192 #endif /* FD_SETSIZE > 1024 */
195 select_select(PyObject
*self
, PyObject
*args
)
197 #ifdef SELECT_USES_HEAP
198 pylist
*rfd2obj
, *wfd2obj
, *efd2obj
;
199 #else /* !SELECT_USES_HEAP */
200 /* XXX: All this should probably be implemented as follows:
201 * - find the highest descriptor we're interested in
204 * See: Stevens, APitUE, $12.5.1
206 pylist rfd2obj
[FD_SETSIZE
+ 1];
207 pylist wfd2obj
[FD_SETSIZE
+ 1];
208 pylist efd2obj
[FD_SETSIZE
+ 1];
209 #endif /* SELECT_USES_HEAP */
210 PyObject
*ifdlist
, *ofdlist
, *efdlist
;
211 PyObject
*ret
= NULL
;
212 PyObject
*tout
= Py_None
;
213 fd_set ifdset
, ofdset
, efdset
;
215 struct timeval tv
, *tvp
;
217 int imax
, omax
, emax
, max
;
220 /* convert arguments */
221 if (!PyArg_UnpackTuple(args
, "select", 3, 4,
222 &ifdlist
, &ofdlist
, &efdlist
, &tout
))
226 tvp
= (struct timeval
*)0;
227 else if (!PyNumber_Check(tout
)) {
228 PyErr_SetString(PyExc_TypeError
,
229 "timeout must be a float or None");
233 timeout
= PyFloat_AsDouble(tout
);
234 if (timeout
== -1 && PyErr_Occurred())
236 if (timeout
> (double)LONG_MAX
) {
237 PyErr_SetString(PyExc_OverflowError
,
238 "timeout period too long");
241 seconds
= (long)timeout
;
242 timeout
= timeout
- (double)seconds
;
244 tv
.tv_usec
= (long)(timeout
* 1E6
);
249 #ifdef SELECT_USES_HEAP
250 /* Allocate memory for the lists */
251 rfd2obj
= PyMem_NEW(pylist
, FD_SETSIZE
+ 1);
252 wfd2obj
= PyMem_NEW(pylist
, FD_SETSIZE
+ 1);
253 efd2obj
= PyMem_NEW(pylist
, FD_SETSIZE
+ 1);
254 if (rfd2obj
== NULL
|| wfd2obj
== NULL
|| efd2obj
== NULL
) {
255 if (rfd2obj
) PyMem_DEL(rfd2obj
);
256 if (wfd2obj
) PyMem_DEL(wfd2obj
);
257 if (efd2obj
) PyMem_DEL(efd2obj
);
258 return PyErr_NoMemory();
260 #endif /* SELECT_USES_HEAP */
261 /* Convert sequences to fd_sets, and get maximum fd number
262 * propagates the Python exception set in seq2set()
264 rfd2obj
[0].sentinel
= -1;
265 wfd2obj
[0].sentinel
= -1;
266 efd2obj
[0].sentinel
= -1;
267 if ((imax
=seq2set(ifdlist
, &ifdset
, rfd2obj
)) < 0)
269 if ((omax
=seq2set(ofdlist
, &ofdset
, wfd2obj
)) < 0)
271 if ((emax
=seq2set(efdlist
, &efdset
, efd2obj
)) < 0)
274 if (omax
> max
) max
= omax
;
275 if (emax
> max
) max
= emax
;
277 Py_BEGIN_ALLOW_THREADS
278 n
= select(max
, &ifdset
, &ofdset
, &efdset
, tvp
);
282 if (n
== SOCKET_ERROR
) {
283 PyErr_SetExcFromWindowsErr(SelectError
, WSAGetLastError());
287 PyErr_SetFromErrno(SelectError
);
291 /* any of these three calls can raise an exception. it's more
292 convenient to test for this after all three calls... but
295 ifdlist
= set2list(&ifdset
, rfd2obj
);
296 ofdlist
= set2list(&ofdset
, wfd2obj
);
297 efdlist
= set2list(&efdset
, efd2obj
);
298 if (PyErr_Occurred())
301 ret
= PyTuple_Pack(3, ifdlist
, ofdlist
, efdlist
);
312 #ifdef SELECT_USES_HEAP
316 #endif /* SELECT_USES_HEAP */
320 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
334 static PyTypeObject poll_Type
;
336 /* Update the malloc'ed array of pollfds to match the dictionary
337 contained within a pollObject. Return 1 on success, 0 on an error.
341 update_ufd_array(pollObject
*self
)
344 PyObject
*key
, *value
;
345 struct pollfd
*old_ufds
= self
->ufds
;
347 self
->ufd_len
= PyDict_Size(self
->dict
);
348 PyMem_RESIZE(self
->ufds
, struct pollfd
, self
->ufd_len
);
349 if (self
->ufds
== NULL
) {
350 self
->ufds
= old_ufds
;
356 while (PyDict_Next(self
->dict
, &pos
, &key
, &value
)) {
357 assert(i
< self
->ufd_len
);
359 self
->ufds
[i
].fd
= (int)PyInt_AsLong(key
);
360 self
->ufds
[i
].events
= (short)(unsigned short)PyInt_AsLong(value
);
363 assert(i
== self
->ufd_len
);
364 self
->ufd_uptodate
= 1;
369 ushort_converter(PyObject
*obj
, void *ptr
)
373 uval
= PyLong_AsUnsignedLong(obj
);
374 if (uval
== (unsigned long)-1 && PyErr_Occurred())
376 if (uval
> USHRT_MAX
) {
377 PyErr_SetString(PyExc_OverflowError
,
378 "Python int too large for C unsigned short");
382 *(unsigned short *)ptr
= Py_SAFE_DOWNCAST(uval
, unsigned long, unsigned short);
386 PyDoc_STRVAR(poll_register_doc
,
387 "register(fd [, eventmask] ) -> None\n\n\
388 Register a file descriptor with the polling object.\n\
389 fd -- either an integer, or an object with a fileno() method returning an\n\
391 events -- an optional bitmask describing the type of events to check for");
394 poll_register(pollObject
*self
, PyObject
*args
)
396 PyObject
*o
, *key
, *value
;
398 unsigned short events
= POLLIN
| POLLPRI
| POLLOUT
;
401 if (!PyArg_ParseTuple(args
, "O|O&:register", &o
, ushort_converter
, &events
))
404 fd
= PyObject_AsFileDescriptor(o
);
405 if (fd
== -1) return NULL
;
407 /* Add entry to the internal dictionary: the key is the
408 file descriptor, and the value is the event mask. */
409 key
= PyInt_FromLong(fd
);
412 value
= PyInt_FromLong(events
);
417 err
= PyDict_SetItem(self
->dict
, key
, value
);
423 self
->ufd_uptodate
= 0;
429 PyDoc_STRVAR(poll_modify_doc
,
430 "modify(fd, eventmask) -> None\n\n\
431 Modify an already registered file descriptor.\n\
432 fd -- either an integer, or an object with a fileno() method returning an\n\
434 events -- an optional bitmask describing the type of events to check for");
437 poll_modify(pollObject
*self
, PyObject
*args
)
439 PyObject
*o
, *key
, *value
;
441 unsigned short events
;
444 if (!PyArg_ParseTuple(args
, "OO&:modify", &o
, ushort_converter
, &events
))
447 fd
= PyObject_AsFileDescriptor(o
);
448 if (fd
== -1) return NULL
;
450 /* Modify registered fd */
451 key
= PyInt_FromLong(fd
);
454 if (PyDict_GetItem(self
->dict
, key
) == NULL
) {
456 PyErr_SetFromErrno(PyExc_IOError
);
459 value
= PyInt_FromLong(events
);
464 err
= PyDict_SetItem(self
->dict
, key
, value
);
470 self
->ufd_uptodate
= 0;
477 PyDoc_STRVAR(poll_unregister_doc
,
478 "unregister(fd) -> None\n\n\
479 Remove a file descriptor being tracked by the polling object.");
482 poll_unregister(pollObject
*self
, PyObject
*o
)
487 fd
= PyObject_AsFileDescriptor( o
);
491 /* Check whether the fd is already in the array */
492 key
= PyInt_FromLong(fd
);
496 if (PyDict_DelItem(self
->dict
, key
) == -1) {
498 /* This will simply raise the KeyError set by PyDict_DelItem
499 if the file descriptor isn't registered. */
504 self
->ufd_uptodate
= 0;
510 PyDoc_STRVAR(poll_poll_doc
,
511 "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
512 Polls the set of registered file descriptors, returning a list containing \n\
513 any descriptors that have events or errors to report.");
516 poll_poll(pollObject
*self
, PyObject
*args
)
518 PyObject
*result_list
= NULL
, *tout
= NULL
;
519 int timeout
= 0, poll_result
, i
, j
;
520 PyObject
*value
= NULL
, *num
= NULL
;
522 if (!PyArg_UnpackTuple(args
, "poll", 0, 1, &tout
)) {
526 /* Check values for timeout */
527 if (tout
== NULL
|| tout
== Py_None
)
529 else if (!PyNumber_Check(tout
)) {
530 PyErr_SetString(PyExc_TypeError
,
531 "timeout must be an integer or None");
535 tout
= PyNumber_Int(tout
);
538 timeout
= _PyInt_AsInt(tout
);
540 if (timeout
== -1 && PyErr_Occurred())
544 /* Avoid concurrent poll() invocation, issue 8865 */
545 if (self
->poll_running
) {
546 PyErr_SetString(PyExc_RuntimeError
,
547 "concurrent poll() invocation");
551 /* Ensure the ufd array is up to date */
552 if (!self
->ufd_uptodate
)
553 if (update_ufd_array(self
) == 0)
556 self
->poll_running
= 1;
559 Py_BEGIN_ALLOW_THREADS
560 poll_result
= poll(self
->ufds
, self
->ufd_len
, timeout
);
563 self
->poll_running
= 0;
565 if (poll_result
< 0) {
566 PyErr_SetFromErrno(SelectError
);
570 /* build the result list */
572 result_list
= PyList_New(poll_result
);
576 for (i
= 0, j
= 0; j
< poll_result
; j
++) {
577 /* skip to the next fired descriptor */
578 while (!self
->ufds
[i
].revents
) {
581 /* if we hit a NULL return, set value to NULL
582 and break out of loop; code at end will
583 clean up result_list */
584 value
= PyTuple_New(2);
587 num
= PyInt_FromLong(self
->ufds
[i
].fd
);
592 PyTuple_SET_ITEM(value
, 0, num
);
594 /* The &0xffff is a workaround for AIX. 'revents'
595 is a 16-bit short, and IBM assigned POLLNVAL
596 to be 0x8000, so the conversion to int results
597 in a negative number. See SF bug #923315. */
598 num
= PyInt_FromLong(self
->ufds
[i
].revents
& 0xffff);
603 PyTuple_SET_ITEM(value
, 1, num
);
604 if ((PyList_SetItem(result_list
, j
, value
)) == -1) {
614 Py_DECREF(result_list
);
618 static PyMethodDef poll_methods
[] = {
619 {"register", (PyCFunction
)poll_register
,
620 METH_VARARGS
, poll_register_doc
},
621 {"modify", (PyCFunction
)poll_modify
,
622 METH_VARARGS
, poll_modify_doc
},
623 {"unregister", (PyCFunction
)poll_unregister
,
624 METH_O
, poll_unregister_doc
},
625 {"poll", (PyCFunction
)poll_poll
,
626 METH_VARARGS
, poll_poll_doc
},
627 {NULL
, NULL
} /* sentinel */
634 self
= PyObject_New(pollObject
, &poll_Type
);
637 /* ufd_uptodate is a Boolean, denoting whether the
638 array pointed to by ufds matches the contents of the dictionary. */
639 self
->ufd_uptodate
= 0;
641 self
->poll_running
= 0;
642 self
->dict
= PyDict_New();
643 if (self
->dict
== NULL
) {
651 poll_dealloc(pollObject
*self
)
653 if (self
->ufds
!= NULL
)
654 PyMem_DEL(self
->ufds
);
655 Py_XDECREF(self
->dict
);
660 poll_getattr(pollObject
*self
, char *name
)
662 return Py_FindMethod(poll_methods
, (PyObject
*)self
, name
);
665 static PyTypeObject poll_Type
= {
666 /* The ob_type field must be initialized in the module init function
667 * to be portable to Windows without using C++. */
668 PyVarObject_HEAD_INIT(NULL
, 0)
669 "select.poll", /*tp_name*/
670 sizeof(pollObject
), /*tp_basicsize*/
673 (destructor
)poll_dealloc
, /*tp_dealloc*/
675 (getattrfunc
)poll_getattr
, /*tp_getattr*/
680 0, /*tp_as_sequence*/
685 PyDoc_STRVAR(poll_doc
,
686 "Returns a polling object, which supports registering and\n\
687 unregistering file descriptors, and then polling them for I/O events.");
690 select_poll(PyObject
*self
, PyObject
*unused
)
692 return (PyObject
*)newPollObject();
697 * On some systems poll() sets errno on invalid file descriptors. We test
698 * for this at runtime because this bug may be fixed or introduced between
701 static int select_have_broken_poll(void)
706 struct pollfd poll_struct
= { 0, POLLIN
|POLLPRI
|POLLOUT
, 0 };
708 /* Create a file descriptor to make invalid */
709 if (pipe(filedes
) < 0) {
712 poll_struct
.fd
= filedes
[0];
715 poll_test
= poll(&poll_struct
, 1, 0);
718 } else if (poll_test
== 0 && poll_struct
.revents
!= POLLNVAL
) {
723 #endif /* __APPLE__ */
725 #endif /* HAVE_POLL */
728 /* **************************************************************************
729 * epoll interface for Linux 2.6
731 * Written by Christian Heimes
732 * Inspired by Twisted's _epoll.pyx and select.poll()
735 #ifdef HAVE_SYS_EPOLL_H
736 #include <sys/epoll.h>
741 SOCKET epfd
; /* epoll control file descriptor */
744 static PyTypeObject pyEpoll_Type
;
745 #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
748 pyepoll_err_closed(void)
750 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed epoll fd");
755 pyepoll_internal_close(pyEpoll_Object
*self
)
758 if (self
->epfd
>= 0) {
759 int epfd
= self
->epfd
;
761 Py_BEGIN_ALLOW_THREADS
770 newPyEpoll_Object(PyTypeObject
*type
, int sizehint
, SOCKET fd
)
772 pyEpoll_Object
*self
;
774 if (sizehint
== -1) {
775 sizehint
= FD_SETSIZE
-1;
777 else if (sizehint
< 1) {
778 PyErr_Format(PyExc_ValueError
,
779 "sizehint must be greater zero, got %d",
784 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
785 self
= (pyEpoll_Object
*) type
->tp_alloc(type
, 0);
790 Py_BEGIN_ALLOW_THREADS
791 self
->epfd
= epoll_create(sizehint
);
797 if (self
->epfd
< 0) {
799 PyErr_SetFromErrno(PyExc_IOError
);
802 return (PyObject
*)self
;
807 pyepoll_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
810 static char *kwlist
[] = {"sizehint", NULL
};
812 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|i:epoll", kwlist
,
816 return newPyEpoll_Object(type
, sizehint
, -1);
821 pyepoll_dealloc(pyEpoll_Object
*self
)
823 (void)pyepoll_internal_close(self
);
824 Py_TYPE(self
)->tp_free(self
);
828 pyepoll_close(pyEpoll_Object
*self
)
830 errno
= pyepoll_internal_close(self
);
832 PyErr_SetFromErrno(PyExc_IOError
);
838 PyDoc_STRVAR(pyepoll_close_doc
,
841 Close the epoll control file descriptor. Further operations on the epoll\n\
842 object will raise an exception.");
845 pyepoll_get_closed(pyEpoll_Object
*self
)
854 pyepoll_fileno(pyEpoll_Object
*self
)
857 return pyepoll_err_closed();
858 return PyInt_FromLong(self
->epfd
);
861 PyDoc_STRVAR(pyepoll_fileno_doc
,
864 Return the epoll control file descriptor.");
867 pyepoll_fromfd(PyObject
*cls
, PyObject
*args
)
871 if (!PyArg_ParseTuple(args
, "i:fromfd", &fd
))
874 return newPyEpoll_Object((PyTypeObject
*)cls
, -1, fd
);
877 PyDoc_STRVAR(pyepoll_fromfd_doc
,
878 "fromfd(fd) -> epoll\n\
880 Create an epoll object from a given control fd.");
883 pyepoll_internal_ctl(int epfd
, int op
, PyObject
*pfd
, unsigned int events
)
885 struct epoll_event ev
;
890 return pyepoll_err_closed();
892 fd
= PyObject_AsFileDescriptor(pfd
);
902 Py_BEGIN_ALLOW_THREADS
903 result
= epoll_ctl(epfd
, op
, fd
, &ev
);
907 /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
908 * operation required a non-NULL pointer in event, even
909 * though this argument is ignored. */
910 Py_BEGIN_ALLOW_THREADS
911 result
= epoll_ctl(epfd
, op
, fd
, &ev
);
912 if (errno
== EBADF
) {
913 /* fd already closed */
925 PyErr_SetFromErrno(PyExc_IOError
);
932 pyepoll_register(pyEpoll_Object
*self
, PyObject
*args
, PyObject
*kwds
)
935 unsigned int events
= EPOLLIN
| EPOLLOUT
| EPOLLPRI
;
936 static char *kwlist
[] = {"fd", "eventmask", NULL
};
938 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|I:register", kwlist
,
943 return pyepoll_internal_ctl(self
->epfd
, EPOLL_CTL_ADD
, pfd
, events
);
946 PyDoc_STRVAR(pyepoll_register_doc
,
947 "register(fd[, eventmask]) -> None\n\
949 Registers a new fd or raises an IOError if the fd is already registered.\n\
950 fd is the target file descriptor of the operation.\n\
951 events is a bit set composed of the various EPOLL constants; the default\n\
952 is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
954 The epoll interface supports all file descriptors that support poll.");
957 pyepoll_modify(pyEpoll_Object
*self
, PyObject
*args
, PyObject
*kwds
)
961 static char *kwlist
[] = {"fd", "eventmask", NULL
};
963 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "OI:modify", kwlist
,
968 return pyepoll_internal_ctl(self
->epfd
, EPOLL_CTL_MOD
, pfd
, events
);
971 PyDoc_STRVAR(pyepoll_modify_doc
,
972 "modify(fd, eventmask) -> None\n\
974 fd is the target file descriptor of the operation\n\
975 events is a bit set composed of the various EPOLL constants");
978 pyepoll_unregister(pyEpoll_Object
*self
, PyObject
*args
, PyObject
*kwds
)
981 static char *kwlist
[] = {"fd", NULL
};
983 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O:unregister", kwlist
,
988 return pyepoll_internal_ctl(self
->epfd
, EPOLL_CTL_DEL
, pfd
, 0);
991 PyDoc_STRVAR(pyepoll_unregister_doc
,
992 "unregister(fd) -> None\n\
994 fd is the target file descriptor of the operation.");
997 pyepoll_poll(pyEpoll_Object
*self
, PyObject
*args
, PyObject
*kwds
)
999 double dtimeout
= -1.;
1003 PyObject
*elist
= NULL
, *etuple
= NULL
;
1004 struct epoll_event
*evs
= NULL
;
1005 static char *kwlist
[] = {"timeout", "maxevents", NULL
};
1008 return pyepoll_err_closed();
1010 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|di:poll", kwlist
,
1011 &dtimeout
, &maxevents
)) {
1018 else if (dtimeout
* 1000.0 > INT_MAX
) {
1019 PyErr_SetString(PyExc_OverflowError
,
1020 "timeout is too large");
1024 timeout
= (int)(dtimeout
* 1000.0);
1027 if (maxevents
== -1) {
1028 maxevents
= FD_SETSIZE
-1;
1030 else if (maxevents
< 1) {
1031 PyErr_Format(PyExc_ValueError
,
1032 "maxevents must be greater than 0, got %d",
1037 evs
= PyMem_New(struct epoll_event
, maxevents
);
1044 Py_BEGIN_ALLOW_THREADS
1045 nfds
= epoll_wait(self
->epfd
, evs
, maxevents
, timeout
);
1046 Py_END_ALLOW_THREADS
1048 PyErr_SetFromErrno(PyExc_IOError
);
1052 elist
= PyList_New(nfds
);
1053 if (elist
== NULL
) {
1057 for (i
= 0; i
< nfds
; i
++) {
1058 etuple
= Py_BuildValue("iI", evs
[i
].data
.fd
, evs
[i
].events
);
1059 if (etuple
== NULL
) {
1063 PyList_SET_ITEM(elist
, i
, etuple
);
1071 PyDoc_STRVAR(pyepoll_poll_doc
,
1072 "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
1074 Wait for events on the epoll file descriptor for a maximum time of timeout\n\
1075 in seconds (as float). -1 makes poll wait indefinitely.\n\
1076 Up to maxevents are returned to the caller.");
1078 static PyMethodDef pyepoll_methods
[] = {
1079 {"fromfd", (PyCFunction
)pyepoll_fromfd
,
1080 METH_VARARGS
| METH_CLASS
, pyepoll_fromfd_doc
},
1081 {"close", (PyCFunction
)pyepoll_close
, METH_NOARGS
,
1083 {"fileno", (PyCFunction
)pyepoll_fileno
, METH_NOARGS
,
1084 pyepoll_fileno_doc
},
1085 {"modify", (PyCFunction
)pyepoll_modify
,
1086 METH_VARARGS
| METH_KEYWORDS
, pyepoll_modify_doc
},
1087 {"register", (PyCFunction
)pyepoll_register
,
1088 METH_VARARGS
| METH_KEYWORDS
, pyepoll_register_doc
},
1089 {"unregister", (PyCFunction
)pyepoll_unregister
,
1090 METH_VARARGS
| METH_KEYWORDS
, pyepoll_unregister_doc
},
1091 {"poll", (PyCFunction
)pyepoll_poll
,
1092 METH_VARARGS
| METH_KEYWORDS
, pyepoll_poll_doc
},
1096 static PyGetSetDef pyepoll_getsetlist
[] = {
1097 {"closed", (getter
)pyepoll_get_closed
, NULL
,
1098 "True if the epoll handler is closed"},
1102 PyDoc_STRVAR(pyepoll_doc
,
1103 "select.epoll([sizehint=-1])\n\
1105 Returns an epolling object\n\
1107 sizehint must be a positive integer or -1 for the default size. The\n\
1108 sizehint is used to optimize internal data structures. It doesn't limit\n\
1109 the maximum number of monitored events.");
1111 static PyTypeObject pyEpoll_Type
= {
1112 PyVarObject_HEAD_INIT(NULL
, 0)
1113 "select.epoll", /* tp_name */
1114 sizeof(pyEpoll_Object
), /* tp_basicsize */
1115 0, /* tp_itemsize */
1116 (destructor
)pyepoll_dealloc
, /* tp_dealloc */
1122 0, /* tp_as_number */
1123 0, /* tp_as_sequence */
1124 0, /* tp_as_mapping */
1128 PyObject_GenericGetAttr
, /* tp_getattro */
1129 0, /* tp_setattro */
1130 0, /* tp_as_buffer */
1131 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1132 pyepoll_doc
, /* tp_doc */
1133 0, /* tp_traverse */
1135 0, /* tp_richcompare */
1136 0, /* tp_weaklistoffset */
1138 0, /* tp_iternext */
1139 pyepoll_methods
, /* tp_methods */
1141 pyepoll_getsetlist
, /* tp_getset */
1144 0, /* tp_descr_get */
1145 0, /* tp_descr_set */
1146 0, /* tp_dictoffset */
1149 pyepoll_new
, /* tp_new */
1153 #endif /* HAVE_EPOLL */
1156 /* **************************************************************************
1157 * kqueue interface for BSD
1159 * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
1160 * All rights reserved.
1162 * Redistribution and use in source and binary forms, with or without
1163 * modification, are permitted provided that the following conditions
1165 * 1. Redistributions of source code must retain the above copyright
1166 * notice, this list of conditions and the following disclaimer.
1167 * 2. Redistributions in binary form must reproduce the above copyright
1168 * notice, this list of conditions and the following disclaimer in the
1169 * documentation and/or other materials provided with the distribution.
1171 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1172 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1173 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1174 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1175 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1176 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1177 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1178 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1179 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1180 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1184 #ifdef HAVE_SYS_EVENT_H
1185 #include <sys/event.h>
1188 PyDoc_STRVAR(kqueue_event_doc
,
1189 "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
1191 This object is the equivalent of the struct kevent for the C API.\n\
1193 See the kqueue manpage for more detailed information about the meaning\n\
1194 of the arguments.\n\
1196 One minor note: while you might hope that udata could store a\n\
1197 reference to a python object, it cannot, because it is impossible to\n\
1198 keep a proper reference count of the object once it's passed into the\n\
1199 kernel. Therefore, I have restricted it to only storing an integer. I\n\
1200 recommend ignoring it and simply using the 'ident' field to key off\n\
1201 of. You could also set up a dictionary on the python side to store a\n\
1202 udata->object mapping.");
1207 } kqueue_event_Object
;
1209 static PyTypeObject kqueue_event_Type
;
1211 #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
1215 SOCKET kqfd
; /* kqueue control fd */
1216 } kqueue_queue_Object
;
1218 static PyTypeObject kqueue_queue_Type
;
1220 #define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))
1222 #if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
1223 # error uintptr_t does not match void *!
1224 #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1225 # define T_UINTPTRT T_ULONGLONG
1226 # define T_INTPTRT T_LONGLONG
1227 # define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong
1228 # define UINTPTRT_FMT_UNIT "K"
1229 # define INTPTRT_FMT_UNIT "L"
1230 #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
1231 # define T_UINTPTRT T_ULONG
1232 # define T_INTPTRT T_LONG
1233 # define PyLong_AsUintptr_t PyLong_AsUnsignedLong
1234 # define UINTPTRT_FMT_UNIT "k"
1235 # define INTPTRT_FMT_UNIT "l"
1236 #elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
1237 # define T_UINTPTRT T_UINT
1238 # define T_INTPTRT T_INT
1239 # define PyLong_AsUintptr_t PyLong_AsUnsignedLong
1240 # define UINTPTRT_FMT_UNIT "I"
1241 # define INTPTRT_FMT_UNIT "i"
1243 # error uintptr_t does not match int, long, or long long!
1247 * kevent is not standard and its members vary across BSDs.
1249 #if !defined(__OpenBSD__)
1250 # define IDENT_TYPE T_UINTPTRT
1251 # define IDENT_CAST Py_intptr_t
1252 # define DATA_TYPE T_INTPTRT
1253 # define DATA_FMT_UNIT INTPTRT_FMT_UNIT
1254 # define IDENT_AsType PyLong_AsUintptr_t
1256 # define IDENT_TYPE T_UINT
1257 # define IDENT_CAST int
1258 # define DATA_TYPE T_INT
1259 # define DATA_FMT_UNIT "i"
1260 # define IDENT_AsType PyLong_AsUnsignedLong
1263 /* Unfortunately, we can't store python objects in udata, because
1264 * kevents in the kernel can be removed without warning, which would
1265 * forever lose the refcount on the object stored with it.
1268 #define KQ_OFF(x) offsetof(kqueue_event_Object, x)
1269 static struct PyMemberDef kqueue_event_members
[] = {
1270 {"ident", IDENT_TYPE
, KQ_OFF(e
.ident
)},
1271 {"filter", T_SHORT
, KQ_OFF(e
.filter
)},
1272 {"flags", T_USHORT
, KQ_OFF(e
.flags
)},
1273 {"fflags", T_UINT
, KQ_OFF(e
.fflags
)},
1274 {"data", DATA_TYPE
, KQ_OFF(e
.data
)},
1275 {"udata", T_UINTPTRT
, KQ_OFF(e
.udata
)},
1276 {NULL
} /* Sentinel */
1282 kqueue_event_repr(kqueue_event_Object
*s
)
1287 "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1288 "data=0x%zd udata=%p>",
1289 (size_t)(s
->e
.ident
), s
->e
.filter
, s
->e
.flags
,
1290 s
->e
.fflags
, (Py_ssize_t
)(s
->e
.data
), s
->e
.udata
);
1291 return PyString_FromString(buf
);
1295 kqueue_event_init(kqueue_event_Object
*self
, PyObject
*args
, PyObject
*kwds
)
1298 static char *kwlist
[] = {"ident", "filter", "flags", "fflags",
1299 "data", "udata", NULL
};
1300 static char *fmt
= "O|hHI" DATA_FMT_UNIT UINTPTRT_FMT_UNIT
":kevent";
1302 EV_SET(&(self
->e
), 0, EVFILT_READ
, EV_ADD
, 0, 0, 0); /* defaults */
1304 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, fmt
, kwlist
,
1305 &pfd
, &(self
->e
.filter
), &(self
->e
.flags
),
1306 &(self
->e
.fflags
), &(self
->e
.data
), &(self
->e
.udata
))) {
1310 if (PyLong_Check(pfd
)
1311 #if IDENT_TYPE == T_UINT
1312 && PyLong_AsUnsignedLong(pfd
) <= UINT_MAX
1315 self
->e
.ident
= IDENT_AsType(pfd
);
1318 self
->e
.ident
= PyObject_AsFileDescriptor(pfd
);
1320 if (PyErr_Occurred()) {
1327 kqueue_event_richcompare(kqueue_event_Object
*s
, kqueue_event_Object
*o
,
1330 Py_intptr_t result
= 0;
1332 if (!kqueue_event_Check(o
)) {
1333 if (op
== Py_EQ
|| op
== Py_NE
) {
1334 PyObject
*res
= op
== Py_EQ
? Py_False
: Py_True
;
1338 PyErr_Format(PyExc_TypeError
,
1339 "can't compare %.200s to %.200s",
1340 Py_TYPE(s
)->tp_name
, Py_TYPE(o
)->tp_name
);
1343 if (((result
= (IDENT_CAST
)(s
->e
.ident
- o
->e
.ident
)) == 0) &&
1344 ((result
= s
->e
.filter
- o
->e
.filter
) == 0) &&
1345 ((result
= s
->e
.flags
- o
->e
.flags
) == 0) &&
1346 ((result
= (int)(s
->e
.fflags
- o
->e
.fflags
)) == 0) &&
1347 ((result
= s
->e
.data
- o
->e
.data
) == 0) &&
1348 ((result
= s
->e
.udata
- o
->e
.udata
) == 0)
1355 result
= (result
== 0);
1358 result
= (result
!= 0);
1361 result
= (result
<= 0);
1364 result
= (result
>= 0);
1367 result
= (result
< 0);
1370 result
= (result
> 0);
1373 return PyBool_FromLong((long)result
);
1376 static PyTypeObject kqueue_event_Type
= {
1377 PyVarObject_HEAD_INIT(NULL
, 0)
1378 "select.kevent", /* tp_name */
1379 sizeof(kqueue_event_Object
), /* tp_basicsize */
1380 0, /* tp_itemsize */
1386 (reprfunc
)kqueue_event_repr
, /* tp_repr */
1387 0, /* tp_as_number */
1388 0, /* tp_as_sequence */
1389 0, /* tp_as_mapping */
1393 0, /* tp_getattro */
1394 0, /* tp_setattro */
1395 0, /* tp_as_buffer */
1396 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1397 kqueue_event_doc
, /* tp_doc */
1398 0, /* tp_traverse */
1400 (richcmpfunc
)kqueue_event_richcompare
, /* tp_richcompare */
1401 0, /* tp_weaklistoffset */
1403 0, /* tp_iternext */
1405 kqueue_event_members
, /* tp_members */
1409 0, /* tp_descr_get */
1410 0, /* tp_descr_set */
1411 0, /* tp_dictoffset */
1412 (initproc
)kqueue_event_init
, /* tp_init */
1419 kqueue_queue_err_closed(void)
1421 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed kqueue fd");
1426 kqueue_queue_internal_close(kqueue_queue_Object
*self
)
1429 if (self
->kqfd
>= 0) {
1430 int kqfd
= self
->kqfd
;
1432 Py_BEGIN_ALLOW_THREADS
1433 if (close(kqfd
) < 0)
1435 Py_END_ALLOW_THREADS
1441 newKqueue_Object(PyTypeObject
*type
, SOCKET fd
)
1443 kqueue_queue_Object
*self
;
1444 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
1445 self
= (kqueue_queue_Object
*) type
->tp_alloc(type
, 0);
1451 Py_BEGIN_ALLOW_THREADS
1452 self
->kqfd
= kqueue();
1453 Py_END_ALLOW_THREADS
1458 if (self
->kqfd
< 0) {
1460 PyErr_SetFromErrno(PyExc_IOError
);
1463 return (PyObject
*)self
;
1467 kqueue_queue_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1470 if ((args
!= NULL
&& PyObject_Size(args
)) ||
1471 (kwds
!= NULL
&& PyObject_Size(kwds
))) {
1472 PyErr_SetString(PyExc_ValueError
,
1473 "select.kqueue doesn't accept arguments");
1477 return newKqueue_Object(type
, -1);
1481 kqueue_queue_dealloc(kqueue_queue_Object
*self
)
1483 kqueue_queue_internal_close(self
);
1484 Py_TYPE(self
)->tp_free(self
);
1488 kqueue_queue_close(kqueue_queue_Object
*self
)
1490 errno
= kqueue_queue_internal_close(self
);
1492 PyErr_SetFromErrno(PyExc_IOError
);
1498 PyDoc_STRVAR(kqueue_queue_close_doc
,
1501 Close the kqueue control file descriptor. Further operations on the kqueue\n\
1502 object will raise an exception.");
1505 kqueue_queue_get_closed(kqueue_queue_Object
*self
)
1514 kqueue_queue_fileno(kqueue_queue_Object
*self
)
1517 return kqueue_queue_err_closed();
1518 return PyInt_FromLong(self
->kqfd
);
1521 PyDoc_STRVAR(kqueue_queue_fileno_doc
,
1524 Return the kqueue control file descriptor.");
1527 kqueue_queue_fromfd(PyObject
*cls
, PyObject
*args
)
1531 if (!PyArg_ParseTuple(args
, "i:fromfd", &fd
))
1534 return newKqueue_Object((PyTypeObject
*)cls
, fd
);
1537 PyDoc_STRVAR(kqueue_queue_fromfd_doc
,
1538 "fromfd(fd) -> kqueue\n\
1540 Create a kqueue object from a given control fd.");
1543 kqueue_queue_control(kqueue_queue_Object
*self
, PyObject
*args
)
1549 PyObject
*otimeout
= NULL
;
1550 PyObject
*ch
= NULL
;
1551 PyObject
*it
= NULL
, *ei
= NULL
;
1552 PyObject
*result
= NULL
;
1553 struct kevent
*evl
= NULL
;
1554 struct kevent
*chl
= NULL
;
1555 struct timespec timeoutspec
;
1556 struct timespec
*ptimeoutspec
;
1559 return kqueue_queue_err_closed();
1561 if (!PyArg_ParseTuple(args
, "Oi|O:control", &ch
, &nevents
, &otimeout
))
1565 PyErr_Format(PyExc_ValueError
,
1566 "Length of eventlist must be 0 or positive, got %d",
1571 if (otimeout
== Py_None
|| otimeout
== NULL
) {
1572 ptimeoutspec
= NULL
;
1574 else if (PyNumber_Check(otimeout
)) {
1578 timeout
= PyFloat_AsDouble(otimeout
);
1579 if (timeout
== -1 && PyErr_Occurred())
1581 if (timeout
> (double)LONG_MAX
) {
1582 PyErr_SetString(PyExc_OverflowError
,
1583 "timeout period too long");
1587 PyErr_SetString(PyExc_ValueError
,
1588 "timeout must be positive or None");
1592 seconds
= (long)timeout
;
1593 timeout
= timeout
- (double)seconds
;
1594 timeoutspec
.tv_sec
= seconds
;
1595 timeoutspec
.tv_nsec
= (long)(timeout
* 1E9
);
1596 ptimeoutspec
= &timeoutspec
;
1599 PyErr_Format(PyExc_TypeError
,
1600 "timeout argument must be an number "
1601 "or None, got %.200s",
1602 Py_TYPE(otimeout
)->tp_name
);
1606 if (ch
!= NULL
&& ch
!= Py_None
) {
1607 it
= PyObject_GetIter(ch
);
1609 PyErr_SetString(PyExc_TypeError
,
1610 "changelist is not iterable");
1613 nchanges
= PyObject_Size(ch
);
1618 chl
= PyMem_New(struct kevent
, nchanges
);
1624 while ((ei
= PyIter_Next(it
)) != NULL
) {
1625 if (!kqueue_event_Check(ei
)) {
1627 PyErr_SetString(PyExc_TypeError
,
1628 "changelist must be an iterable of "
1629 "select.kevent objects");
1632 chl
[i
++] = ((kqueue_event_Object
*)ei
)->e
;
1641 evl
= PyMem_New(struct kevent
, nevents
);
1648 Py_BEGIN_ALLOW_THREADS
1649 gotevents
= kevent(self
->kqfd
, chl
, nchanges
,
1650 evl
, nevents
, ptimeoutspec
);
1651 Py_END_ALLOW_THREADS
1653 if (gotevents
== -1) {
1654 PyErr_SetFromErrno(PyExc_OSError
);
1658 result
= PyList_New(gotevents
);
1659 if (result
== NULL
) {
1663 for (i
= 0; i
< gotevents
; i
++) {
1664 kqueue_event_Object
*ch
;
1666 ch
= PyObject_New(kqueue_event_Object
, &kqueue_event_Type
);
1671 PyList_SET_ITEM(result
, i
, (PyObject
*)ch
);
1685 PyDoc_STRVAR(kqueue_queue_control_doc
,
1686 "control(changelist, max_events[, timeout=None]) -> eventlist\n\
1688 Calls the kernel kevent function.\n\
1689 - changelist must be a list of kevent objects describing the changes\n\
1690 to be made to the kernel's watch list or None.\n\
1691 - max_events lets you specify the maximum number of events that the\n\
1692 kernel will return.\n\
1693 - timeout is the maximum time to wait in seconds, or else None,\n\
1694 to wait forever. timeout accepts floats for smaller timeouts, too.");
1697 static PyMethodDef kqueue_queue_methods
[] = {
1698 {"fromfd", (PyCFunction
)kqueue_queue_fromfd
,
1699 METH_VARARGS
| METH_CLASS
, kqueue_queue_fromfd_doc
},
1700 {"close", (PyCFunction
)kqueue_queue_close
, METH_NOARGS
,
1701 kqueue_queue_close_doc
},
1702 {"fileno", (PyCFunction
)kqueue_queue_fileno
, METH_NOARGS
,
1703 kqueue_queue_fileno_doc
},
1704 {"control", (PyCFunction
)kqueue_queue_control
,
1705 METH_VARARGS
, kqueue_queue_control_doc
},
1709 static PyGetSetDef kqueue_queue_getsetlist
[] = {
1710 {"closed", (getter
)kqueue_queue_get_closed
, NULL
,
1711 "True if the kqueue handler is closed"},
1715 PyDoc_STRVAR(kqueue_queue_doc
,
1716 "Kqueue syscall wrapper.\n\
1718 For example, to start watching a socket for input:\n\
1719 >>> kq = kqueue()\n\
1720 >>> sock = socket()\n\
1721 >>> sock.connect((host, port))\n\
1722 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
1724 To wait one second for it to become writeable:\n\
1725 >>> kq.control(None, 1, 1000)\n\
1727 To stop listening:\n\
1728 >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
1730 static PyTypeObject kqueue_queue_Type
= {
1731 PyVarObject_HEAD_INIT(NULL
, 0)
1732 "select.kqueue", /* tp_name */
1733 sizeof(kqueue_queue_Object
), /* tp_basicsize */
1734 0, /* tp_itemsize */
1735 (destructor
)kqueue_queue_dealloc
, /* tp_dealloc */
1741 0, /* tp_as_number */
1742 0, /* tp_as_sequence */
1743 0, /* tp_as_mapping */
1747 0, /* tp_getattro */
1748 0, /* tp_setattro */
1749 0, /* tp_as_buffer */
1750 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1751 kqueue_queue_doc
, /* tp_doc */
1752 0, /* tp_traverse */
1754 0, /* tp_richcompare */
1755 0, /* tp_weaklistoffset */
1757 0, /* tp_iternext */
1758 kqueue_queue_methods
, /* tp_methods */
1760 kqueue_queue_getsetlist
, /* tp_getset */
1763 0, /* tp_descr_get */
1764 0, /* tp_descr_set */
1765 0, /* tp_dictoffset */
1768 kqueue_queue_new
, /* tp_new */
1772 #endif /* HAVE_KQUEUE */
1773 /* ************************************************************************ */
1775 PyDoc_STRVAR(select_doc
,
1776 "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
1778 Wait until one or more file descriptors are ready for some kind of I/O.\n\
1779 The first three arguments are sequences of file descriptors to be waited for:\n\
1780 rlist -- wait until ready for reading\n\
1781 wlist -- wait until ready for writing\n\
1782 xlist -- wait for an ``exceptional condition''\n\
1783 If only one kind of condition is required, pass [] for the other lists.\n\
1784 A file descriptor is either a socket or file object, or a small integer\n\
1785 gotten from a fileno() method call on one of those.\n\
1787 The optional 4th argument specifies a timeout in seconds; it may be\n\
1788 a floating point number to specify fractions of seconds. If it is absent\n\
1789 or None, the call will never time out.\n\
1791 The return value is a tuple of three lists corresponding to the first three\n\
1792 arguments; each contains the subset of the corresponding file descriptors\n\
1795 *** IMPORTANT NOTICE ***\n\
1796 On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
1797 descriptors can be used.");
1799 static PyMethodDef select_methods
[] = {
1800 {"select", select_select
, METH_VARARGS
, select_doc
},
1801 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
1802 {"poll", select_poll
, METH_NOARGS
, poll_doc
},
1803 #endif /* HAVE_POLL */
1804 {0, 0}, /* sentinel */
1807 PyDoc_STRVAR(module_doc
,
1808 "This module supports asynchronous I/O on multiple file descriptors.\n\
1810 *** IMPORTANT NOTICE ***\n\
1811 On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.");
1817 m
= Py_InitModule3("select", select_methods
, module_doc
);
1821 SelectError
= PyErr_NewException("select.error", NULL
, NULL
);
1822 Py_INCREF(SelectError
);
1823 PyModule_AddObject(m
, "error", SelectError
);
1826 #ifdef HAVE_BROKEN_PIPE_BUF
1828 #define PIPE_BUF 512
1830 PyModule_AddIntConstant(m
, "PIPE_BUF", PIPE_BUF
);
1833 #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
1835 if (select_have_broken_poll()) {
1836 if (PyObject_DelAttrString(m
, "poll") == -1) {
1843 Py_TYPE(&poll_Type
) = &PyType_Type
;
1844 PyModule_AddIntConstant(m
, "POLLIN", POLLIN
);
1845 PyModule_AddIntConstant(m
, "POLLPRI", POLLPRI
);
1846 PyModule_AddIntConstant(m
, "POLLOUT", POLLOUT
);
1847 PyModule_AddIntConstant(m
, "POLLERR", POLLERR
);
1848 PyModule_AddIntConstant(m
, "POLLHUP", POLLHUP
);
1849 PyModule_AddIntConstant(m
, "POLLNVAL", POLLNVAL
);
1852 PyModule_AddIntConstant(m
, "POLLRDNORM", POLLRDNORM
);
1855 PyModule_AddIntConstant(m
, "POLLRDBAND", POLLRDBAND
);
1858 PyModule_AddIntConstant(m
, "POLLWRNORM", POLLWRNORM
);
1861 PyModule_AddIntConstant(m
, "POLLWRBAND", POLLWRBAND
);
1864 PyModule_AddIntConstant(m
, "POLLMSG", POLLMSG
);
1867 #endif /* HAVE_POLL */
1870 Py_TYPE(&pyEpoll_Type
) = &PyType_Type
;
1871 if (PyType_Ready(&pyEpoll_Type
) < 0)
1874 Py_INCREF(&pyEpoll_Type
);
1875 PyModule_AddObject(m
, "epoll", (PyObject
*) &pyEpoll_Type
);
1877 PyModule_AddIntConstant(m
, "EPOLLIN", EPOLLIN
);
1878 PyModule_AddIntConstant(m
, "EPOLLOUT", EPOLLOUT
);
1879 PyModule_AddIntConstant(m
, "EPOLLPRI", EPOLLPRI
);
1880 PyModule_AddIntConstant(m
, "EPOLLERR", EPOLLERR
);
1881 PyModule_AddIntConstant(m
, "EPOLLHUP", EPOLLHUP
);
1882 PyModule_AddIntConstant(m
, "EPOLLET", EPOLLET
);
1885 PyModule_AddIntConstant(m
, "EPOLLONESHOT", EPOLLONESHOT
);
1887 /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
1888 PyModule_AddIntConstant(m
, "EPOLLRDNORM", EPOLLRDNORM
);
1889 PyModule_AddIntConstant(m
, "EPOLLRDBAND", EPOLLRDBAND
);
1890 PyModule_AddIntConstant(m
, "EPOLLWRNORM", EPOLLWRNORM
);
1891 PyModule_AddIntConstant(m
, "EPOLLWRBAND", EPOLLWRBAND
);
1892 PyModule_AddIntConstant(m
, "EPOLLMSG", EPOLLMSG
);
1893 #endif /* HAVE_EPOLL */
1896 kqueue_event_Type
.tp_new
= PyType_GenericNew
;
1897 Py_TYPE(&kqueue_event_Type
) = &PyType_Type
;
1898 if(PyType_Ready(&kqueue_event_Type
) < 0)
1901 Py_INCREF(&kqueue_event_Type
);
1902 PyModule_AddObject(m
, "kevent", (PyObject
*)&kqueue_event_Type
);
1904 Py_TYPE(&kqueue_queue_Type
) = &PyType_Type
;
1905 if(PyType_Ready(&kqueue_queue_Type
) < 0)
1907 Py_INCREF(&kqueue_queue_Type
);
1908 PyModule_AddObject(m
, "kqueue", (PyObject
*)&kqueue_queue_Type
);
1911 PyModule_AddIntConstant(m
, "KQ_FILTER_READ", EVFILT_READ
);
1912 PyModule_AddIntConstant(m
, "KQ_FILTER_WRITE", EVFILT_WRITE
);
1913 PyModule_AddIntConstant(m
, "KQ_FILTER_AIO", EVFILT_AIO
);
1914 PyModule_AddIntConstant(m
, "KQ_FILTER_VNODE", EVFILT_VNODE
);
1915 PyModule_AddIntConstant(m
, "KQ_FILTER_PROC", EVFILT_PROC
);
1916 #ifdef EVFILT_NETDEV
1917 PyModule_AddIntConstant(m
, "KQ_FILTER_NETDEV", EVFILT_NETDEV
);
1919 PyModule_AddIntConstant(m
, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL
);
1920 PyModule_AddIntConstant(m
, "KQ_FILTER_TIMER", EVFILT_TIMER
);
1923 PyModule_AddIntConstant(m
, "KQ_EV_ADD", EV_ADD
);
1924 PyModule_AddIntConstant(m
, "KQ_EV_DELETE", EV_DELETE
);
1925 PyModule_AddIntConstant(m
, "KQ_EV_ENABLE", EV_ENABLE
);
1926 PyModule_AddIntConstant(m
, "KQ_EV_DISABLE", EV_DISABLE
);
1927 PyModule_AddIntConstant(m
, "KQ_EV_ONESHOT", EV_ONESHOT
);
1928 PyModule_AddIntConstant(m
, "KQ_EV_CLEAR", EV_CLEAR
);
1930 PyModule_AddIntConstant(m
, "KQ_EV_SYSFLAGS", EV_SYSFLAGS
);
1931 PyModule_AddIntConstant(m
, "KQ_EV_FLAG1", EV_FLAG1
);
1933 PyModule_AddIntConstant(m
, "KQ_EV_EOF", EV_EOF
);
1934 PyModule_AddIntConstant(m
, "KQ_EV_ERROR", EV_ERROR
);
1936 /* READ WRITE filter flag */
1937 PyModule_AddIntConstant(m
, "KQ_NOTE_LOWAT", NOTE_LOWAT
);
1939 /* VNODE filter flags */
1940 PyModule_AddIntConstant(m
, "KQ_NOTE_DELETE", NOTE_DELETE
);
1941 PyModule_AddIntConstant(m
, "KQ_NOTE_WRITE", NOTE_WRITE
);
1942 PyModule_AddIntConstant(m
, "KQ_NOTE_EXTEND", NOTE_EXTEND
);
1943 PyModule_AddIntConstant(m
, "KQ_NOTE_ATTRIB", NOTE_ATTRIB
);
1944 PyModule_AddIntConstant(m
, "KQ_NOTE_LINK", NOTE_LINK
);
1945 PyModule_AddIntConstant(m
, "KQ_NOTE_RENAME", NOTE_RENAME
);
1946 PyModule_AddIntConstant(m
, "KQ_NOTE_REVOKE", NOTE_REVOKE
);
1948 /* PROC filter flags */
1949 PyModule_AddIntConstant(m
, "KQ_NOTE_EXIT", NOTE_EXIT
);
1950 PyModule_AddIntConstant(m
, "KQ_NOTE_FORK", NOTE_FORK
);
1951 PyModule_AddIntConstant(m
, "KQ_NOTE_EXEC", NOTE_EXEC
);
1952 PyModule_AddIntConstant(m
, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK
);
1953 PyModule_AddIntConstant(m
, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK
);
1955 PyModule_AddIntConstant(m
, "KQ_NOTE_TRACK", NOTE_TRACK
);
1956 PyModule_AddIntConstant(m
, "KQ_NOTE_CHILD", NOTE_CHILD
);
1957 PyModule_AddIntConstant(m
, "KQ_NOTE_TRACKERR", NOTE_TRACKERR
);
1959 /* NETDEV filter flags */
1960 #ifdef EVFILT_NETDEV
1961 PyModule_AddIntConstant(m
, "KQ_NOTE_LINKUP", NOTE_LINKUP
);
1962 PyModule_AddIntConstant(m
, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN
);
1963 PyModule_AddIntConstant(m
, "KQ_NOTE_LINKINV", NOTE_LINKINV
);
1966 #endif /* HAVE_KQUEUE */