[project @ 2001-12-05 12:20:39 by simonmar]
[ghc-hetmet.git] / ghc / lib / std / cbits / inputReady.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * hWaitForInput Runtime Support
5  */
6
7 /* select and supporting types is not Posix */
8 /* #include "PosixSource.h" */
9 #include "HsStd.h"
10
11 /*
12  * inputReady(fd) checks to see whether input is available on the file
13  * descriptor 'fd'.  Input meaning 'can I safely read at least a
14  * *character* from this file object without blocking?'
15  */
16 int
17 inputReady(int fd, int msecs, int isSock)
18 {
19   if 
20 #ifndef mingw32_TARGET_OS
21     ( 1 ) {
22 #else
23     ( isSock ) {
24 #endif
25     int maxfd, ready;
26     fd_set rfd;
27     struct timeval tv;
28
29     FD_ZERO(&rfd);
30     FD_SET(fd, &rfd);
31
32     /* select() will consider the descriptor set in the range of 0 to
33      * (maxfd-1) 
34      */
35     maxfd = fd + 1;
36     tv.tv_sec  = msecs / 1000;
37     tv.tv_usec = msecs % 1000;
38
39     while ((ready = select(maxfd, &rfd, NULL, NULL, &tv)) < 0 ) {
40       if (errno != EINTR ) {
41           return -1;
42       }
43    }
44
45     /* 1 => Input ready, 0 => not ready, -1 => error */
46     return (ready);
47 #ifdef mingw32_TARGET_OS
48     } else {
49       DWORD rc;
50       HANDLE hFile = (HANDLE)_get_osfhandle(fd);
51     
52       rc = MsgWaitForMultipleObjects( 1,
53                                       &hFile,
54                                       FALSE, /* wait all */
55                                       msecs, /*millisecs*/
56                                       QS_ALLEVENTS);
57     
58       /* 1 => Input ready, 0 => not ready, -1 => error */
59       switch (rc) {
60        case WAIT_TIMEOUT: return 0;
61        case WAIT_OBJECT_0: return 1;
62        default: return -1;
63       }
64     }
65 #endif
66   }}