home *** CD-ROM | disk | FTP | other *** search
/ Complete Linux / Complete Linux.iso / docs / devel / tcl / tclx7_31.z / tclx7_31 / tcldev / tclX7.3a-p1 / src / tclXselect.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-19  |  14.1 KB  |  445 lines

  1. /*
  2.  * tclXselect.c
  3.  *
  4.  * Extended Tcl file I/O commands.
  5.  *-----------------------------------------------------------------------------
  6.  * Copyright 1991-1993 Karl Lehenbauer and Mark Diekhans.
  7.  *
  8.  * Permission to use, copy, modify, and distribute this software and its
  9.  * documentation for any purpose and without fee is hereby granted, provided
  10.  * that the above copyright notice appear in all copies.  Karl Lehenbauer and
  11.  * Mark Diekhans make no representations about the suitability of this
  12.  * software for any purpose.  It is provided "as is" without express or
  13.  * implied warranty.
  14.  *-----------------------------------------------------------------------------
  15.  * $Id: tclXselect.c,v 3.0 1993/11/19 06:59:13 markd Rel $
  16.  *-----------------------------------------------------------------------------
  17.  */
  18.  
  19. #include "tclExtdInt.h"
  20.  
  21. #ifdef HAVE_SELECT
  22.  
  23. #ifdef HAVE_SYS_SELECT_H
  24. #   include <sys/select.h>
  25. #endif
  26.  
  27. /*
  28.  * Cheat a little to avoid configure checking for floor being prototyped.
  29.  * This breaks with GNU libc headers...really should check with autoconf.
  30.  */
  31.  
  32. #ifndef __GNU_LIBRARY__
  33. extern
  34. double floor ();
  35. #endif
  36.  
  37. /*
  38.  * A couple of systems (Xenix and older SCO unix) have bzero hidden away
  39.  * in the X library that we don't use, but the select macros use bzero.
  40.  * Make them use memset with this magic.
  41.  */
  42. #ifndef HAVE_BZERO
  43. #    define bzero(to,length)    memset(to,'\0',length)
  44. #endif
  45.  
  46. /*
  47.  * Macro to probe the stdio buffer to see if any data is pending in the
  48.  * buffer.  Different versions are provided for System V and BSD stdio.
  49.  */
  50.  
  51. #ifdef linux
  52. #   define READ_DATA_PENDING(fp) (fp->_egptr != fp->_gptr)
  53. #endif
  54. #if (!defined (READ_DATA_PENDING)) && defined __SLBF
  55. #   define READ_DATA_PENDING(fp) (fp->_r > 0)
  56. #endif
  57. #if !defined (READ_DATA_PENDING)
  58. #   define READ_DATA_PENDING(fp) (fp->_cnt != 0)
  59. #endif
  60.  
  61. /*
  62.  * A few systems (A/UX 2.0) have select but no macros, define em in this case.
  63.  */
  64. #ifndef FD_SET
  65. #   define FD_SET(fd,fdset)     (fdset)->fds_bits[0] |= (1<<(fd))
  66. #   define FD_CLR(fd,fdset)     (fdset)->fds_bits[0] &= ~(1<<(fd))
  67. #   define FD_ZERO(fdset)       (fdset)->fds_bits[0] = 0
  68. #   define FD_ISSET(fd,fdset)   (((fdset)->fds_bits[0]) & (1<<(fd)))
  69. #endif
  70.  
  71. /*
  72.  * Prototypes of internal functions.
  73.  */
  74. static int
  75. ParseSelectFileList _ANSI_ARGS_((Tcl_Interp *interp,
  76.                                  char       *handleList,
  77.                                  fd_set     *fileDescSetPtr,
  78.                                  FILE     ***fileDescListPtr,
  79.                                  int        *maxFileIdPtr));
  80.  
  81. static int
  82. FindPendingData _ANSI_ARGS_((int         fileDescCnt,
  83.                              FILE      **fileDescList,
  84.                              fd_set     *fileDescSetPtr));
  85.  
  86. static char *
  87. ReturnSelectedFileList _ANSI_ARGS_((fd_set     *fileDescSetPtr,
  88.                                     fd_set     *fileDescSet2Ptr,
  89.                                     int         fileDescCnt,
  90.                                     FILE      **fileDescList));
  91.  
  92.  
  93. /*
  94.  *-----------------------------------------------------------------------------
  95.  *
  96.  * ParseSelectFileList --
  97.  *
  98.  *   Parse a list of file handles for select.
  99.  *
  100.  * Parameters:
  101.  *   o interp (O) - Error messages are returned in the result.
  102.  *   o handleList (I) - The list of file handles to parse, may be empty.
  103.  *   o fileDescSetPtr (O) - The select fd_set for the parsed handles is
  104.  *     filled in.  Should be cleared before this procedure is called.
  105.  *   o fileDescListPtr (O) - A pointer to a dynamically allocated list of
  106.  *     the FILE ptrs that are in the set.  If the list is empty, NULL is
  107.  *     returned.
  108.  *   o maxFileIdPtr (I/O) - If a file id greater than the current value is
  109.  *     encountered, it will be set to that file id.
  110.  * Returns:
  111.  *   The number of files in the list, or -1 if an error occured.
  112.  *-----------------------------------------------------------------------------
  113.  */
  114. static int
  115. ParseSelectFileList (interp, handleList, fileDescSetPtr, fileDescListPtr,
  116.                      maxFileIdPtr)
  117.     Tcl_Interp *interp;
  118.     char       *handleList;
  119.     fd_set     *fileDescSetPtr;
  120.     FILE     ***fileDescListPtr;
  121.     int        *maxFileIdPtr;
  122. {
  123.     int    handleCnt, idx;
  124.     char **handleArgv;
  125.     FILE **fileDescList;
  126.  
  127.     /*
  128.      * Optimize empty list handling.
  129.      */
  130.     if (handleList [0] == '\0') {
  131.         *fileDescListPtr = NULL;
  132.         return 0;
  133.     }
  134.  
  135.     if (Tcl_SplitList (interp, handleList, &handleCnt, &handleArgv) != TCL_OK)
  136.         return -1;
  137.  
  138.     /*
  139.      * Handle case of an empty list.
  140.      */
  141.     if (handleCnt == 0) {
  142.         *fileDescListPtr = NULL;
  143.         ckfree ((char *) handleArgv);
  144.         return 0;
  145.     }
  146.  
  147.     fileDescList = (FILE **) ckalloc (sizeof (FILE *) * handleCnt);
  148.  
  149.     for (idx = 0; idx < handleCnt; idx++) {
  150.         FILE *filePtr;
  151.         int   fileId;
  152.  
  153.         if (Tcl_GetOpenFile (interp, handleArgv [idx],
  154.                              FALSE, FALSE,  /* No checking */
  155.                              &filePtr) != TCL_OK) {
  156.             ckfree ((char *) handleArgv);
  157.             ckfree ((char *) fileDescList);
  158.             return -1;
  159.         }
  160.         fileId = fileno (filePtr);
  161.         fileDescList [idx] = filePtr;
  162.  
  163.         FD_SET (fileId, fileDescSetPtr);
  164.         if (fileId > *maxFileIdPtr)
  165.             *maxFileIdPtr = fileId;
  166.     }
  167.  
  168.     *fileDescListPtr = fileDescList;
  169.     ckfree ((char *) handleArgv);
  170.     return handleCnt;
  171. }
  172.  
  173. /*
  174.  *-----------------------------------------------------------------------------
  175.  *
  176.  * FindPendingData --
  177.  *
  178.  *   Scan a list of read file descriptors to determine if any of them
  179.  *   have data pending in their stdio buffers.
  180.  *
  181.  * Parameters:
  182.  *   o fileDescCnt (I) - Number of descriptors in the list.
  183.  *   o fileDescListPtr (I) - A pointer to a list of the FILE pointers for
  184.  *     files that are in the set.
  185.  *   o fileDescSetPtr (I) - A select fd_set with will have a bit set for
  186.  *     every file that has data pending it its buffer.
  187.  * Returns:
  188.  *   TRUE if any where found that had pending data, FALSE if none were found.
  189.  *-----------------------------------------------------------------------------
  190.  */
  191. static int
  192. FindPendingData (fileDescCnt, fileDescList, fileDescSetPtr)
  193.     int         fileDescCnt;
  194.     FILE      **fileDescList;
  195.     fd_set     *fileDescSetPtr;
  196. {
  197.     int idx, found = FALSE;
  198.  
  199.     FD_ZERO (fileDescSetPtr);
  200.  
  201.     for (idx = 0; idx < fileDescCnt; idx++) {
  202.         if (READ_DATA_PENDING (fileDescList [idx])) {
  203.             FD_SET (fileno (fileDescList [idx]), fileDescSetPtr);
  204.             found = TRUE;
  205.         }
  206.     }
  207.     return found;
  208. }
  209.  
  210. /*
  211.  *-----------------------------------------------------------------------------
  212.  *
  213.  * ReturnSelectedFileList --
  214.  *
  215.  *   Take the resulting file descriptor sets from a select, and the
  216.  *   list of file descritpors and build up a list of Tcl file handles.
  217.  *
  218.  * Parameters:
  219.  *   o fileDescSetPtr (I) - The select fd_set.
  220.  *   o fileDescSet2Ptr (I) - Pointer to a second descriptor to also check
  221.  *     (their may be overlap).  NULL if no second set.
  222.  *   o fileDescCnt (I) - Number of descriptors in the list.
  223.  *   o fileDescListPtr (I) - A pointer to a list of the FILE pointers for
  224.  *     files that are in the set.  If the list is empty, NULL is returned.
  225.  * Returns:
  226.  *   A dynamicly allocated list of file handles.  If the handles are empty,
  227.  *   it still returns a NULL list to make clean up easy.
  228.  *-----------------------------------------------------------------------------
  229.  */
  230. static char *
  231. ReturnSelectedFileList (fileDescSetPtr, fileDescSet2Ptr, fileDescCnt,
  232.                         fileDescList) 
  233.     fd_set     *fileDescSetPtr;
  234.     fd_set     *fileDescSet2Ptr;
  235.     int         fileDescCnt;
  236.     FILE      **fileDescList;
  237. {
  238.     int    idx, handleCnt, fileNum;
  239.     char  *fileHandleList;
  240.     char **fileHandleArgv, *nextByte;
  241.  
  242.     /*
  243.      * Special case the empty list.
  244.      */
  245.     if (fileDescCnt == 0) {
  246.         fileHandleList = ckalloc (1);
  247.         fileHandleList [0] = '\0';
  248.         return fileHandleList;
  249.     }
  250.  
  251.     /*
  252.      * Allocate enough room to hold the argv plus all the `fileNNN' strings
  253.      */
  254.     fileHandleArgv = (char **)
  255.         ckalloc ((fileDescCnt * sizeof (char *)) + (9 * fileDescCnt));
  256.     nextByte = ((char *) fileHandleArgv) + (fileDescCnt * sizeof (char *));
  257.  
  258.     handleCnt = 0;
  259.     for (idx = 0; idx < fileDescCnt; idx++) {
  260.         fileNum = fileno (fileDescList [idx]);
  261.  
  262.         if (FD_ISSET (fileNum, fileDescSetPtr) ||
  263.             (fileDescSet2Ptr != NULL &&
  264.              FD_ISSET (fileNum, fileDescSet2Ptr))) {
  265.  
  266.             fileHandleArgv [handleCnt] = nextByte;  /* Allocate storage */
  267.             nextByte += 8;
  268.             sprintf (fileHandleArgv [handleCnt], "file%d", fileNum);
  269.             handleCnt++;
  270.         }
  271.     }
  272.  
  273.     fileHandleList = Tcl_Merge (handleCnt, fileHandleArgv);
  274.     ckfree ((char *) fileHandleArgv);
  275.  
  276.     return fileHandleList;
  277. }
  278.  
  279. /*
  280.  *-----------------------------------------------------------------------------
  281.  *
  282.  * Tcl_SelectCmd --
  283.  *  Implements the select TCL command:
  284.  *      select readhandles ?writehandles? ?excepthandles? ?timeout?
  285.  *
  286.  *  This command is extra smart in the fact that it checks for read data
  287.  * pending in the stdio buffer first before doing a select.
  288.  *   
  289.  * Results:
  290.  *     A list in the form:
  291.  *        {readhandles writehandles excepthandles}
  292.  *     or {} it the timeout expired.
  293.  *-----------------------------------------------------------------------------
  294.  */
  295. int
  296. Tcl_SelectCmd (clientData, interp, argc, argv)
  297.     ClientData  clientData;
  298.     Tcl_Interp *interp;
  299.     int         argc;
  300.     char      **argv;
  301. {
  302.  
  303.     fd_set readFdSet,            writeFdSet,            exceptFdSet;
  304.     int    readDescCnt = 0,      writeDescCnt = 0,      exceptDescCnt = 0;
  305.     FILE **readDescList = NULL,**writeDescList = NULL,**exceptDescList = NULL;
  306.     fd_set readFdSet2;
  307.     char  *retListArgv [3];
  308.  
  309.     int             numSelected, maxFileId = 0, pending;
  310.     int             result = TCL_ERROR;
  311.     struct timeval  timeoutRec;
  312.     struct timeval *timeoutRecPtr;
  313.  
  314.  
  315.     if (argc < 2) {
  316.         Tcl_AppendResult (interp, tclXWrongArgs, argv [0], 
  317.                           " readFileIds ?writeFileIds? ?exceptFileIds?",
  318.                           " ?timeout?", (char *) NULL);
  319.         return TCL_ERROR;
  320.     }
  321.     
  322.     /*
  323.      * Parse the file handles and set everything up for the select call.
  324.      */
  325.     FD_ZERO (&readFdSet);
  326.     FD_ZERO (&writeFdSet);
  327.     FD_ZERO (&exceptFdSet);
  328.     readDescCnt = ParseSelectFileList (interp, argv [1], &readFdSet, 
  329.                                        &readDescList, &maxFileId);
  330.     if (readDescCnt < 0)
  331.         goto exitPoint;
  332.     if (argc > 2) {
  333.         writeDescCnt = ParseSelectFileList (interp, argv [2], &writeFdSet, 
  334.                                             &writeDescList, &maxFileId);
  335.         if (writeDescCnt < 0)
  336.             goto exitPoint;
  337.     }
  338.     if (argc > 3) {
  339.         exceptDescCnt = ParseSelectFileList (interp, argv [3], &exceptFdSet, 
  340.                                              &exceptDescList, &maxFileId);
  341.         if (exceptDescCnt < 0)
  342.             goto exitPoint;
  343.     }
  344.     
  345.     /*
  346.      * Get the time out.  Zero is different that not specified.
  347.      */
  348.     timeoutRecPtr = NULL;
  349.     if ((argc > 4) && (argv [4][0] != '\0')) {
  350.         double  timeout, seconds, microseconds;
  351.  
  352.         if (Tcl_GetDouble (interp, argv [4], &timeout) != TCL_OK)
  353.             goto exitPoint;
  354.         if (timeout < 0) {
  355.             Tcl_AppendResult (interp, "timeout must be greater than or equal",
  356.                               " to zero", (char *) NULL);
  357.             goto exitPoint;
  358.         }
  359.         seconds = floor (timeout);
  360.         microseconds = (timeout - seconds) * 1000000.0;
  361.         timeoutRec.tv_sec = seconds;
  362.         timeoutRec.tv_usec = microseconds;
  363.         timeoutRecPtr = &timeoutRec;
  364.     }
  365.  
  366.     /*
  367.      * Check if any data is pending in the read stdio buffers.  If there is,
  368.      * then do the select, but don't block in it.
  369.      */
  370.  
  371.     pending = FindPendingData (readDescCnt, readDescList, &readFdSet2);
  372.     if (pending) {
  373.         timeoutRec.tv_sec = 0;
  374.         timeoutRec.tv_usec = 0;
  375.         timeoutRecPtr = &timeoutRec;
  376.     }
  377.  
  378.     /*
  379.      * All set, do the select.
  380.      */
  381.     numSelected = select (maxFileId + 1, &readFdSet, &writeFdSet, &exceptFdSet,
  382.                           timeoutRecPtr);
  383.     if (numSelected < 0) {
  384.         interp->result = Tcl_PosixError (interp);
  385.         goto exitPoint;
  386.     }
  387.  
  388.     /*
  389.      * Return the result, either a 3 element list, or leave the result
  390.      * empty if the timeout occured.
  391.      */
  392.     if (numSelected > 0 || pending) {
  393.         retListArgv [0] = ReturnSelectedFileList (&readFdSet,
  394.                                                   &readFdSet2,
  395.                                                   readDescCnt,
  396.                                                   readDescList);
  397.         retListArgv [1] = ReturnSelectedFileList (&writeFdSet,
  398.                                                   NULL,
  399.                                                   writeDescCnt, 
  400.                                                   writeDescList);
  401.         retListArgv [2] = ReturnSelectedFileList (&exceptFdSet,
  402.                                                   NULL,
  403.                                                   exceptDescCnt, 
  404.                                                   exceptDescList);
  405.         Tcl_SetResult (interp, Tcl_Merge (3, retListArgv), TCL_DYNAMIC); 
  406.         ckfree ((char *) retListArgv [0]);
  407.         ckfree ((char *) retListArgv [1]);
  408.         ckfree ((char *) retListArgv [2]);
  409.     }
  410.  
  411.     result = TCL_OK;
  412.  
  413. exitPoint:
  414.     if (readDescList != NULL)
  415.         ckfree ((char *) readDescList);
  416.     if (writeDescList != NULL)
  417.         ckfree ((char *) writeDescList);
  418.     if (exceptDescList != NULL)
  419.         ckfree ((char *) exceptDescList);
  420.     return result;
  421.  
  422. }
  423. #else
  424. /*
  425.  *-----------------------------------------------------------------------------
  426.  *
  427.  * Tcl_SelectCmd --
  428.  *     Dummy select command that returns an error for systems that don't
  429.  *     have select.
  430.  *-----------------------------------------------------------------------------
  431.  */
  432. int
  433. Tcl_SelectCmd (clientData, interp, argc, argv)
  434.     ClientData  clientData;
  435.     Tcl_Interp *interp;
  436.     int         argc;
  437.     char      **argv;
  438. {
  439.     Tcl_AppendResult (interp, 
  440.                       "select is not available on this version of Unix",
  441.                       (char *) NULL);
  442.     return TCL_ERROR;
  443. }
  444. #endif
  445.