summaryrefslogtreecommitdiff
path: root/ghc/lib/std/cbits/inputReady.c
blob: a206d159ac6c5bc5629a475487be28680f16fefd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* 
 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
 *
 * hWaitForInput Runtime Support
 */

/* select and supporting types is not Posix */
/* #include "PosixSource.h" */
#include "HsStd.h"

/*
 * inputReady(fd) checks to see whether input is available on the file
 * descriptor 'fd'.  Input meaning 'can I safely read at least a
 * *character* from this file object without blocking?'
 */
int
inputReady(int fd, int msecs, int isSock)
{
  if 
#ifndef mingw32_TARGET_OS
    ( 1 ) {
#else
    ( isSock ) {
    int maxfd, ready;
    fd_set rfd;
    struct timeval tv;

    FD_ZERO(&rfd);
    FD_SET(fd, &rfd);

    /* select() will consider the descriptor set in the range of 0 to
     * (maxfd-1) 
     */
    maxfd = fd + 1;
    tv.tv_sec  = msecs / 1000;
    tv.tv_usec = msecs % 1000;

    while ((ready = select(maxfd, &rfd, NULL, NULL, &tv)) < 0 ) {
      if (errno != EINTR ) {
          return -1;
      }
   }

    /* 1 => Input ready, 0 => not ready, -1 => error */
    return (ready);
#endif
#ifdef mingw32_TARGET_OS
    } else {
      DWORD rc;
      HANDLE hFile = (HANDLE)_get_osfhandle(fd);
    
      rc = MsgWaitForMultipleObjects( 1,
				      &hFile,
				      FALSE, /* wait all */
			              msecs, /*millisecs*/
				      QS_ALLEVENTS);
    
      /* 1 => Input ready, 0 => not ready, -1 => error */
      switch (rc) {
       case WAIT_TIMEOUT: return 0;
       case WAIT_OBJECT_0: return 1;
       default: return -1;
      }
    }
#endif
  }}