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