home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / selectmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  19.1 KB  |  810 lines

  1.  
  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
  7.    >= 0.
  8. */
  9.  
  10. #include "Python.h"
  11.  
  12. #ifdef HAVE_UNISTD_H
  13. #include <unistd.h>
  14. #endif
  15. #ifdef HAVE_POLL_H
  16. #include <poll.h>
  17. #endif
  18.  
  19. #ifdef __sgi
  20. /* This is missing from unistd.h */
  21. extern void bzero(void *, int);
  22. #endif
  23.  
  24. #ifndef DONT_HAVE_SYS_TYPES_H
  25. #include <sys/types.h>
  26. #endif
  27.  
  28. #if defined(PYOS_OS2)
  29. #include <sys/time.h>
  30. #include <utils.h>
  31. #endif
  32.  
  33. #ifdef MS_WINDOWS
  34. #include <winsock.h>
  35. #else
  36. #ifdef __BEOS__
  37. #include <net/socket.h>
  38. #define SOCKET int
  39. #else
  40. #define SOCKET int
  41. #endif
  42. #endif
  43.  
  44. #if defined(AMITCP) || defined(INET225)
  45. #include <proto/socket.h>
  46. #endif
  47.  
  48. static PyObject *SelectError;
  49.  
  50. /* list of Python objects and their file descriptor */
  51. typedef struct {
  52.     PyObject *obj;                 /* owned reference */
  53.     SOCKET fd;
  54.     int sentinel;                 /* -1 == sentinel */
  55. } pylist;
  56.  
  57. static void
  58. reap_obj(pylist fd2obj[FD_SETSIZE + 3])
  59. {
  60.     int i;
  61.     for (i = 0; i < FD_SETSIZE + 3 && fd2obj[i].sentinel >= 0; i++) {
  62.         Py_XDECREF(fd2obj[i].obj);
  63.         fd2obj[i].obj = NULL;
  64.     }
  65.     fd2obj[0].sentinel = -1;
  66. }
  67.  
  68.  
  69. /* returns -1 and sets the Python exception if an error occurred, otherwise
  70.    returns a number >= 0
  71. */
  72. static int
  73. list2set(PyObject *list, fd_set *set, pylist fd2obj[FD_SETSIZE + 3])
  74. {
  75.     int i;
  76.     int max = -1;
  77.     int index = 0;
  78.     int len = PyList_Size(list);
  79.     PyObject* o = NULL;
  80.  
  81.     fd2obj[0].obj = (PyObject*)0;         /* set list to zero size */
  82.     FD_ZERO(set);
  83.  
  84.     for (i = 0; i < len; i++)  {
  85.         SOCKET v;
  86.  
  87.         /* any intervening fileno() calls could decr this refcnt */
  88.         if (!(o = PyList_GetItem(list, i)))
  89.                     return -1;
  90.  
  91.         Py_INCREF(o);
  92.         v = PyObject_AsFileDescriptor( o );
  93.         if (v == -1) goto finally;
  94.  
  95. #if defined(_MSC_VER)
  96.         max = 0;             /* not used for Win32 */
  97. #else  /* !_MSC_VER */
  98.         if (v < 0 || v >= FD_SETSIZE) {
  99.             PyErr_SetString(PyExc_ValueError,
  100.                     "filedescriptor out of range in select()");
  101.             goto finally;
  102.         }
  103.         if (v > max)
  104.             max = v;
  105. #endif /* _MSC_VER */
  106.         FD_SET(v, set);
  107.  
  108.         /* add object and its file descriptor to the list */
  109.         if (index >= FD_SETSIZE) {
  110.             PyErr_SetString(PyExc_ValueError,
  111.                       "too many file descriptors in select()");
  112.             goto finally;
  113.         }
  114.         fd2obj[index].obj = o;
  115.         fd2obj[index].fd = v;
  116.         fd2obj[index].sentinel = 0;
  117.         fd2obj[++index].sentinel = -1;
  118.     }
  119.     return max+1;
  120.  
  121.   finally:
  122.     Py_XDECREF(o);
  123.     return -1;
  124. }
  125.  
  126. /* returns NULL and sets the Python exception if an error occurred */
  127. static PyObject *
  128. set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 3])
  129. {
  130.     int i, j, count=0;
  131.     PyObject *list, *o;
  132.     SOCKET fd;
  133.  
  134.     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
  135.         if (FD_ISSET(fd2obj[j].fd, set))
  136.             count++;
  137.     }
  138.     list = PyList_New(count);
  139.     if (!list)
  140.         return NULL;
  141.  
  142.     i = 0;
  143.     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
  144.         fd = fd2obj[j].fd;
  145.         if (FD_ISSET(fd, set)) {
  146. #ifndef _MSC_VER
  147.             if (fd > FD_SETSIZE) {
  148.                 PyErr_SetString(PyExc_SystemError,
  149.                "filedescriptor out of range returned in select()");
  150.                 goto finally;
  151.             }
  152. #endif
  153.             o = fd2obj[j].obj;
  154.             fd2obj[j].obj = NULL;
  155.             /* transfer ownership */
  156.             if (PyList_SetItem(list, i, o) < 0)
  157.                 goto finally;
  158.  
  159.             i++;
  160.         }
  161.     }
  162.     return list;
  163.   finally:
  164.     Py_DECREF(list);
  165.     return NULL;
  166. }
  167.  
  168.  
  169. #if defined(AMITCP) || defined(INET225)
  170. /* Amiga's version of select: WaitSelect()/selectwait() support */
  171. /* (additional 5th parameter: signal waitmask) */
  172. static PyObject *
  173. select_select(PyObject *self, PyObject *args)
  174. {
  175. #if defined (MS_WINDOWS) || defined (_AMIGA)
  176.     /* This would be an awful lot of stack space on Windows! */
  177.     pylist *rfd2obj, *wfd2obj, *efd2obj;
  178. #else
  179.     pylist rfd2obj[FD_SETSIZE + 3];
  180.     pylist wfd2obj[FD_SETSIZE + 3];
  181.     pylist efd2obj[FD_SETSIZE + 3];
  182. #endif
  183.     PyObject *ifdlist, *ofdlist, *efdlist;
  184.     PyObject *ret = NULL;
  185.     PyObject *tout = Py_None;
  186.     fd_set ifdset, ofdset, efdset;
  187.     double timeout;
  188.     struct timeval tv, *tvp;
  189.     int seconds;
  190.     int imax, omax, emax, max;
  191.     int n;
  192.     ULONG waitmask=0;
  193.     BOOL do_waitmask = FALSE;
  194.  
  195.     /* convert arguments */
  196.     if (!PyArg_ParseTuple(args, "OOO|Oi",
  197.                   &ifdlist, &ofdlist, &efdlist, &tout, &waitmask))
  198.         return NULL;
  199.  
  200.     if (tout == Py_None)
  201.         tvp = (struct timeval *)0;
  202.     else if (!PyArg_Parse(tout, "d", &timeout)) {
  203.         PyErr_SetString(PyExc_TypeError,
  204.                 "timeout must be a float or None");
  205.         return NULL;
  206.     }
  207.     else {
  208.         seconds = (int)timeout;
  209.         timeout = timeout - (double)seconds;
  210.         tv.tv_sec = seconds;
  211.         tv.tv_usec = (int)(timeout*1000000.0);
  212.         tvp = &tv;
  213.     }
  214.  
  215.     if(waitmask) do_waitmask=TRUE;
  216.  
  217.     /* sanity check first three arguments */
  218.     if (!PyList_Check(ifdlist) ||
  219.         !PyList_Check(ofdlist) ||
  220.         !PyList_Check(efdlist))
  221.     {
  222.         PyErr_SetString(PyExc_TypeError,
  223.                 "arguments 1-3 must be lists");
  224.         return NULL;
  225.     }
  226.  
  227. #if defined(MS_WINDOWS) || defined (_AMIGA)
  228.     /* Allocate memory for the lists */
  229.     rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  230.     wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  231.     efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  232.     if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
  233.         if (rfd2obj) PyMem_DEL(rfd2obj);
  234.         if (wfd2obj) PyMem_DEL(wfd2obj);
  235.         if (efd2obj) PyMem_DEL(efd2obj);
  236.         return NULL;
  237.     }
  238. #endif
  239.     /* Convert lists to fd_sets, and get maximum fd number
  240.      * propagates the Python exception set in list2set()
  241.      */
  242.     rfd2obj[0].sentinel = -1;
  243.     wfd2obj[0].sentinel = -1;
  244.     efd2obj[0].sentinel = -1;
  245.     if ((imax=list2set(ifdlist, &ifdset, rfd2obj)) < 0) 
  246.         goto finally;
  247.     if ((omax=list2set(ofdlist, &ofdset, wfd2obj)) < 0) 
  248.         goto finally;
  249.     if ((emax=list2set(efdlist, &efdset, efd2obj)) < 0) 
  250.         goto finally;
  251.     max = imax;
  252.     if (omax > max) max = omax;
  253.     if (emax > max) max = emax;
  254.  
  255.     Py_BEGIN_ALLOW_THREADS
  256. #ifdef AMITCP
  257.     n = WaitSelect(max, &ifdset, &ofdset, &efdset, tvp, &waitmask);
  258. #else /* INET225 */
  259.     n = selectwait(max, &ifdset, &ofdset, &efdset, tvp, &waitmask);
  260. #endif    
  261.     Py_END_ALLOW_THREADS
  262.  
  263.     if (n < 0) {
  264.         PyErr_SetFromErrno(SelectError);
  265.     }
  266.     else if (n == 0) {
  267.                 /* optimization */
  268.         ifdlist = PyList_New(0);
  269.         if (ifdlist) {
  270.             if(do_waitmask) ret=Py_BuildValue("OOOi", ifdlist, ifdlist, ifdlist, waitmask);
  271.             else ret = Py_BuildValue("OOO", ifdlist, ifdlist, ifdlist);
  272.             Py_DECREF(ifdlist);
  273.         }
  274.     }
  275.     else {
  276.         /* any of these three calls can raise an exception.  it's more
  277.            convenient to test for this after all three calls... but
  278.            is that acceptable?
  279.         */
  280.         ifdlist = set2list(&ifdset, rfd2obj);
  281.         ofdlist = set2list(&ofdset, wfd2obj);
  282.         efdlist = set2list(&efdset, efd2obj);
  283.         if (PyErr_Occurred())
  284.             ret = NULL;
  285.         else
  286.         {
  287.             if(do_waitmask) ret=Py_BuildValue("OOOi", ifdlist, ofdlist, efdlist, waitmask);
  288.             else ret = Py_BuildValue("OOO", ifdlist, ofdlist, efdlist);
  289.         }
  290.  
  291.         Py_DECREF(ifdlist);
  292.         Py_DECREF(ofdlist);
  293.         Py_DECREF(efdlist);
  294.     }
  295.     
  296.   finally:
  297.     reap_obj(rfd2obj);
  298.     reap_obj(wfd2obj);
  299.     reap_obj(efd2obj);
  300. #if defined(MS_WINDOWS) || defined (_AMIGA)
  301.     PyMem_DEL(rfd2obj);
  302.     PyMem_DEL(wfd2obj);
  303.     PyMem_DEL(efd2obj);
  304. #endif
  305.     return ret;
  306. }
  307.  
  308. #else /* ! AMITCP || INET225 */
  309. /* This is the select function for all other platforms */
  310.     
  311. static PyObject *
  312. select_select(PyObject *self, PyObject *args)
  313. {
  314. #ifdef MS_WINDOWS
  315.     /* This would be an awful lot of stack space on Windows! */
  316.     pylist *rfd2obj, *wfd2obj, *efd2obj;
  317. #else
  318.     pylist rfd2obj[FD_SETSIZE + 3];
  319.     pylist wfd2obj[FD_SETSIZE + 3];
  320.     pylist efd2obj[FD_SETSIZE + 3];
  321. #endif
  322.     PyObject *ifdlist, *ofdlist, *efdlist;
  323.     PyObject *ret = NULL;
  324.     PyObject *tout = Py_None;
  325.     fd_set ifdset, ofdset, efdset;
  326.     double timeout;
  327.     struct timeval tv, *tvp;
  328.     long seconds;
  329.     int imax, omax, emax, max;
  330.     int n;
  331.  
  332.     /* convert arguments */
  333.     if (!PyArg_ParseTuple(args, "OOO|O:select",
  334.                   &ifdlist, &ofdlist, &efdlist, &tout))
  335.         return NULL;
  336.  
  337.     if (tout == Py_None)
  338.         tvp = (struct timeval *)0;
  339.     else if (!PyArg_Parse(tout, "d", &timeout)) {
  340.         PyErr_SetString(PyExc_TypeError,
  341.                 "timeout must be a float or None");
  342.         return NULL;
  343.     }
  344.     else {
  345.         if (timeout > (double)LONG_MAX) {
  346.             PyErr_SetString(PyExc_OverflowError, "timeout period too long");
  347.             return NULL;
  348.         }
  349.         seconds = (long)timeout;
  350.         timeout = timeout - (double)seconds;
  351.         tv.tv_sec = seconds;
  352.         tv.tv_usec = (long)(timeout*1000000.0);
  353.         tvp = &tv;
  354.     }
  355.  
  356.     /* sanity check first three arguments */
  357.     if (!PyList_Check(ifdlist) ||
  358.         !PyList_Check(ofdlist) ||
  359.         !PyList_Check(efdlist))
  360.     {
  361.         PyErr_SetString(PyExc_TypeError,
  362.                 "arguments 1-3 must be lists");
  363.         return NULL;
  364.     }
  365.  
  366. #ifdef MS_WINDOWS
  367.     /* Allocate memory for the lists */
  368.     rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  369.     wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  370.     efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 3);
  371.     if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
  372.         if (rfd2obj) PyMem_DEL(rfd2obj);
  373.         if (wfd2obj) PyMem_DEL(wfd2obj);
  374.         if (efd2obj) PyMem_DEL(efd2obj);
  375.         return NULL;
  376.     }
  377. #endif
  378.     /* Convert lists to fd_sets, and get maximum fd number
  379.      * propagates the Python exception set in list2set()
  380.      */
  381.     rfd2obj[0].sentinel = -1;
  382.     wfd2obj[0].sentinel = -1;
  383.     efd2obj[0].sentinel = -1;
  384.     if ((imax=list2set(ifdlist, &ifdset, rfd2obj)) < 0) 
  385.         goto finally;
  386.     if ((omax=list2set(ofdlist, &ofdset, wfd2obj)) < 0) 
  387.         goto finally;
  388.     if ((emax=list2set(efdlist, &efdset, efd2obj)) < 0) 
  389.         goto finally;
  390.     max = imax;
  391.     if (omax > max) max = omax;
  392.     if (emax > max) max = emax;
  393.  
  394.     Py_BEGIN_ALLOW_THREADS
  395.     n = select(max, &ifdset, &ofdset, &efdset, tvp);
  396.     Py_END_ALLOW_THREADS
  397.  
  398.     if (n < 0) {
  399.         PyErr_SetFromErrno(SelectError);
  400.     }
  401.     else if (n == 0) {
  402.                 /* optimization */
  403.         ifdlist = PyList_New(0);
  404.         if (ifdlist) {
  405.             ret = Py_BuildValue("OOO", ifdlist, ifdlist, ifdlist);
  406.             Py_DECREF(ifdlist);
  407.         }
  408.     }
  409.     else {
  410.         /* any of these three calls can raise an exception.  it's more
  411.            convenient to test for this after all three calls... but
  412.            is that acceptable?
  413.         */
  414.         ifdlist = set2list(&ifdset, rfd2obj);
  415.         ofdlist = set2list(&ofdset, wfd2obj);
  416.         efdlist = set2list(&efdset, efd2obj);
  417.         if (PyErr_Occurred())
  418.             ret = NULL;
  419.         else
  420.             ret = Py_BuildValue("OOO", ifdlist, ofdlist, efdlist);
  421.  
  422.         Py_DECREF(ifdlist);
  423.         Py_DECREF(ofdlist);
  424.         Py_DECREF(efdlist);
  425.     }
  426.     
  427.   finally:
  428.     reap_obj(rfd2obj);
  429.     reap_obj(wfd2obj);
  430.     reap_obj(efd2obj);
  431. #ifdef MS_WINDOWS
  432.     PyMem_DEL(rfd2obj);
  433.     PyMem_DEL(wfd2obj);
  434.     PyMem_DEL(efd2obj);
  435. #endif
  436.     return ret;
  437. }
  438.  
  439. #endif /* !AMITCP || INET225 */
  440.  
  441.  
  442. #ifdef HAVE_POLL
  443. /* 
  444.  * poll() support
  445.  */
  446.  
  447. typedef struct {
  448.     PyObject_HEAD
  449.     PyObject *dict;
  450.     int ufd_uptodate; 
  451.     int ufd_len;
  452.         struct pollfd *ufds;
  453. } pollObject;
  454.  
  455. staticforward PyTypeObject poll_Type;
  456.  
  457. /* Update the malloc'ed array of pollfds to match the dictionary 
  458.    contained within a pollObject.  Return 1 on success, 0 on an error.
  459. */
  460.  
  461. static int
  462. update_ufd_array(pollObject *self)
  463. {
  464.     int i, j, pos;
  465.     PyObject *key, *value;
  466.  
  467.     self->ufd_len = PyDict_Size(self->dict);
  468.     PyMem_Resize(self->ufds, struct pollfd, self->ufd_len);
  469.     if (self->ufds == NULL) {
  470.         PyErr_NoMemory();
  471.         return 0;
  472.     }
  473.  
  474.     i = pos = 0;
  475.     while ((j = PyDict_Next(self->dict, &pos, &key, &value))) {
  476.         self->ufds[i].fd = PyInt_AsLong(key);
  477.         self->ufds[i].events = PyInt_AsLong(value);
  478.         i++;
  479.     }
  480.     self->ufd_uptodate = 1;
  481.     return 1;
  482. }
  483.  
  484. static char poll_register_doc[] =
  485. "register(fd [, eventmask] ) -> None\n\n\
  486. Register a file descriptor with the polling object.\n\
  487. fd -- either an integer, or an object with a fileno() method returning an int.\n\
  488. events -- an optional bitmask describing the type of events to check for";
  489.  
  490. static PyObject *
  491. poll_register(pollObject *self, PyObject *args) 
  492. {
  493.     PyObject *o, *key, *value;
  494.     int fd, events = POLLIN | POLLPRI | POLLOUT;
  495.  
  496.     if (!PyArg_ParseTuple(args, "O|i", &o, &events)) {
  497.         return NULL;
  498.     }
  499.   
  500.     fd = PyObject_AsFileDescriptor(o);
  501.     if (fd == -1) return NULL;
  502.  
  503.     /* Add entry to the internal dictionary: the key is the 
  504.        file descriptor, and the value is the event mask. */
  505.     if ( (NULL == (key = PyInt_FromLong(fd))) ||
  506.          (NULL == (value = PyInt_FromLong(events))) ||
  507.          (PyDict_SetItem(self->dict, key, value)) == -1) {
  508.         return NULL;
  509.     }
  510.     self->ufd_uptodate = 0;
  511.                
  512.     Py_INCREF(Py_None);
  513.     return Py_None;
  514. }
  515.  
  516. static char poll_unregister_doc[] =
  517. "unregister(fd) -> None\n\n\
  518. Remove a file descriptor being tracked by the polling object.";
  519.  
  520. static PyObject *
  521. poll_unregister(pollObject *self, PyObject *args) 
  522. {
  523.     PyObject *o, *key;
  524.     int fd;
  525.  
  526.     if (!PyArg_ParseTuple(args, "O", &o)) {
  527.         return NULL;
  528.     }
  529.   
  530.     fd = PyObject_AsFileDescriptor( o );
  531.     if (fd == -1) 
  532.         return NULL;
  533.  
  534.     /* Check whether the fd is already in the array */
  535.     key = PyInt_FromLong(fd);
  536.     if (key == NULL) 
  537.         return NULL;
  538.  
  539.     if (PyDict_DelItem(self->dict, key) == -1) {
  540.         Py_DECREF(key);
  541.         /* This will simply raise the KeyError set by PyDict_DelItem
  542.            if the file descriptor isn't registered. */
  543.         return NULL;
  544.     }
  545.  
  546.     Py_DECREF(key);
  547.     self->ufd_uptodate = 0;
  548.  
  549.     Py_INCREF(Py_None);
  550.     return Py_None;
  551. }
  552.  
  553. static char poll_poll_doc[] =
  554. "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
  555. Polls the set of registered file descriptors, returning a list containing \n\
  556. any descriptors that have events or errors to report.";
  557.  
  558. static PyObject *
  559. poll_poll(pollObject *self, PyObject *args) 
  560. {
  561.     PyObject *result_list = NULL, *tout = NULL;
  562.     int timeout = 0, poll_result, i, j;
  563.     PyObject *value = NULL, *num = NULL;
  564.  
  565.     if (!PyArg_ParseTuple(args, "|O", &tout)) {
  566.         return NULL;
  567.     }
  568.  
  569.     /* Check values for timeout */
  570.     if (tout == NULL || tout == Py_None)
  571.         timeout = -1;
  572.     else if (!PyArg_Parse(tout, "i", &timeout)) {
  573.         PyErr_SetString(PyExc_TypeError,
  574.                 "timeout must be an integer or None");
  575.         return NULL;
  576.     }
  577.  
  578.     /* Ensure the ufd array is up to date */
  579.     if (!self->ufd_uptodate) 
  580.         if (update_ufd_array(self) == 0)
  581.             return NULL;
  582.  
  583.     /* call poll() */
  584.     Py_BEGIN_ALLOW_THREADS;
  585.     poll_result = poll(self->ufds, self->ufd_len, timeout);
  586.     Py_END_ALLOW_THREADS;
  587.  
  588.     if (poll_result < 0) {
  589.         PyErr_SetFromErrno(SelectError);
  590.         return NULL;
  591.     } 
  592.        
  593.     /* build the result list */
  594.   
  595.     result_list = PyList_New(poll_result);
  596.     if (!result_list) 
  597.         return NULL;
  598.     else {
  599.         for (i = 0, j = 0; j < poll_result; j++) {
  600.              /* skip to the next fired descriptor */
  601.              while (!self->ufds[i].revents) {
  602.                  i++;
  603.              }
  604.             /* if we hit a NULL return, set value to NULL
  605.                and break out of loop; code at end will
  606.                clean up result_list */
  607.             value = PyTuple_New(2);
  608.             if (value == NULL)
  609.                 goto error;
  610.             num = PyInt_FromLong(self->ufds[i].fd);
  611.             if (num == NULL) {
  612.                 Py_DECREF(value);
  613.                 goto error;
  614.             }
  615.             PyTuple_SET_ITEM(value, 0, num);
  616.  
  617.             num = PyInt_FromLong(self->ufds[i].revents);
  618.             if (num == NULL) {
  619.                 Py_DECREF(value);
  620.                 goto error;
  621.             }
  622.             PyTuple_SET_ITEM(value, 1, num);
  623.              if ((PyList_SetItem(result_list, j, value)) == -1) {
  624.                 Py_DECREF(value);
  625.                 goto error;
  626.              }
  627.              i++;
  628.          }
  629.      }
  630.      return result_list;
  631.  
  632.   error:
  633.     Py_DECREF(result_list);
  634.     return NULL;
  635. }
  636.  
  637. static PyMethodDef poll_methods[] = {
  638.     {"register",    (PyCFunction)poll_register,    
  639.      METH_VARARGS,  poll_register_doc},
  640.     {"unregister",    (PyCFunction)poll_unregister,    
  641.      METH_VARARGS,  poll_unregister_doc},
  642.     {"poll",    (PyCFunction)poll_poll,    
  643.      METH_VARARGS,  poll_poll_doc},
  644.     {NULL,        NULL}        /* sentinel */
  645. };
  646.  
  647. static pollObject *
  648. newPollObject(void)
  649. {
  650.         pollObject *self;
  651.     self = PyObject_New(pollObject, &poll_Type);
  652.     if (self == NULL)
  653.         return NULL;
  654.     /* ufd_uptodate is a Boolean, denoting whether the 
  655.        array pointed to by ufds matches the contents of the dictionary. */
  656.     self->ufd_uptodate = 0;
  657.     self->ufds = NULL;
  658.     self->dict = PyDict_New();
  659.     if (self->dict == NULL) {
  660.         Py_DECREF(self);
  661.         return NULL;
  662.     }
  663.     return self;
  664. }
  665.  
  666. static void
  667. poll_dealloc(pollObject *self)
  668. {
  669.     if (self->ufds != NULL)
  670.         PyMem_DEL(self->ufds);
  671.     Py_XDECREF(self->dict);
  672.       PyObject_Del(self);
  673. }
  674.  
  675. static PyObject *
  676. poll_getattr(pollObject *self, char *name)
  677. {
  678.     return Py_FindMethod(poll_methods, (PyObject *)self, name);
  679. }
  680.  
  681. statichere PyTypeObject poll_Type = {
  682.     /* The ob_type field must be initialized in the module init function
  683.      * to be portable to Windows without using C++. */
  684.     PyObject_HEAD_INIT(NULL)
  685.     0,            /*ob_size*/
  686.     "poll",            /*tp_name*/
  687.     sizeof(pollObject),    /*tp_basicsize*/
  688.     0,            /*tp_itemsize*/
  689.     /* methods */
  690.     (destructor)poll_dealloc, /*tp_dealloc*/
  691.     0,            /*tp_print*/
  692.     (getattrfunc)poll_getattr, /*tp_getattr*/
  693.     0,                      /*tp_setattr*/
  694.     0,            /*tp_compare*/
  695.     0,            /*tp_repr*/
  696.     0,            /*tp_as_number*/
  697.     0,            /*tp_as_sequence*/
  698.     0,            /*tp_as_mapping*/
  699.     0,            /*tp_hash*/
  700. };
  701.  
  702. static char poll_doc[] = 
  703. "Returns a polling object, which supports registering and\n\
  704. unregistering file descriptors, and then polling them for I/O events.";
  705.  
  706. static PyObject *
  707. select_poll(PyObject *self, PyObject *args)
  708. {
  709.     pollObject *rv;
  710.     
  711.     if (!PyArg_ParseTuple(args, ":poll"))
  712.         return NULL;
  713.     rv = newPollObject();
  714.     if ( rv == NULL )
  715.         return NULL;
  716.     return (PyObject *)rv;
  717. }
  718. #endif /* HAVE_POLL */
  719.  
  720. static char select_doc[] =
  721. "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
  722. \n\
  723. Wait until one or more file descriptors are ready for some kind of I/O.\n\
  724. The first three arguments are lists of file descriptors to be waited for:\n\
  725. rlist -- wait until ready for reading\n\
  726. wlist -- wait until ready for writing\n\
  727. xlist -- wait for an ``exceptional condition''\n\
  728. If only one kind of condition is required, pass [] for the other lists.\n\
  729. A file descriptor is either a socket or file object, or a small integer\n\
  730. gotten from a fileno() method call on one of those.\n\
  731. \n\
  732. The optional 4th argument specifies a timeout in seconds; it may be\n\
  733. a floating point number to specify fractions of seconds.  If it is absent\n\
  734. or None, the call will never time out.\n\
  735. \n\
  736. The return value is a tuple of three lists corresponding to the first three\n\
  737. arguments; each contains the subset of the corresponding file descriptors\n\
  738. that are ready.\n\
  739. \n\
  740. *** IMPORTANT NOTICE ***\n\
  741. On Windows, only sockets are supported; on Unix, all file descriptors.";
  742.  
  743. static PyMethodDef select_methods[] = {
  744.     {"select",    select_select, METH_VARARGS, select_doc},
  745. #ifdef HAVE_POLL
  746.     {"poll",    select_poll,   METH_VARARGS, poll_doc},
  747. #endif /* HAVE_POLL */
  748.     {0,      0},                 /* sentinel */
  749. };
  750.  
  751. static char module_doc[] =
  752. "This module supports asynchronous I/O on multiple file descriptors.\n\
  753. \n\
  754. *** IMPORTANT NOTICE ***\n\
  755. On Windows, only sockets are supported; on Unix, all file descriptors.";
  756.  
  757. /*
  758.  * Convenience routine to export an integer value.
  759.  * For simplicity, errors (which are unlikely anyway) are ignored.
  760.  */
  761.  
  762. static void
  763. insint(PyObject *d, char *name, int value)
  764. {
  765.     PyObject *v = PyInt_FromLong((long) value);
  766.     if (v == NULL) {
  767.         /* Don't bother reporting this error */
  768.         PyErr_Clear();
  769.     }
  770.     else {
  771.         PyDict_SetItemString(d, name, v);
  772.         Py_DECREF(v);
  773.     }
  774. }
  775.  
  776. DL_EXPORT(void)
  777. initselect(void)
  778. {
  779.     PyObject *m, *d;
  780.     m = Py_InitModule3("select", select_methods, module_doc);
  781.     d = PyModule_GetDict(m);
  782.     SelectError = PyErr_NewException("select.error", NULL, NULL);
  783.     PyDict_SetItemString(d, "error", SelectError);
  784. #ifdef HAVE_POLL
  785.     poll_Type.ob_type = &PyType_Type;
  786.     insint(d, "POLLIN", POLLIN);
  787.     insint(d, "POLLPRI", POLLPRI);
  788.     insint(d, "POLLOUT", POLLOUT);
  789.     insint(d, "POLLERR", POLLERR);
  790.     insint(d, "POLLHUP", POLLHUP);
  791.     insint(d, "POLLNVAL", POLLNVAL);
  792.  
  793. #ifdef POLLRDNORM
  794.     insint(d, "POLLRDNORM", POLLRDNORM);
  795. #endif
  796. #ifdef POLLRDBAND
  797.     insint(d, "POLLRDBAND", POLLRDBAND);
  798. #endif
  799. #ifdef POLLWRNORM
  800.     insint(d, "POLLWRNORM", POLLWRNORM);
  801. #endif
  802. #ifdef POLLWRBAND
  803.     insint(d, "POLLWRBAND", POLLWRBAND);
  804. #endif
  805. #ifdef POLLMSG
  806.     insint(d, "POLLMSG", POLLMSG);
  807. #endif
  808. #endif /* HAVE_POLL */
  809. }
  810.