f827fe5def79ec1f5deb0a0521f8847281d4bdd4
[packages/old-locale.git] / cbits / inputReady.c
1 /*
2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-2002
3 *
4 * hWaitForInput Runtime Support
5 */
6
7 /* select and supporting types is not Posix */
8 /* #include "PosixSource.h" */
9 #include "HsBase.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 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)
21 ( isSock ) {
22 #else
23 ( 1 ) {
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) * 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 }
48 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)
49 else {
50 DWORD rc;
51 HANDLE hFile = (HANDLE)_get_osfhandle(fd);
52 DWORD avail;
53
54 // WaitForMultipleObjects() works for Console input, but it
55 // doesn't work for pipes (it always returns WAIT_OBJECT_0
56 // even when no data is available). There doesn't seem to be
57 // an easy way to distinguish the two kinds of HANDLE, so we
58 // try to detect pipe input first, and if that fails we try
59 // WaitForMultipleObjects().
60 //
61 rc = PeekNamedPipe( hFile, NULL, 0, NULL, &avail, NULL );
62 if (rc != 0) {
63 if (avail != 0) {
64 return 1;
65 } else {
66 return 0;
67 }
68 } else {
69 rc = GetLastError();
70 if (rc == ERROR_BROKEN_PIPE) {
71 return 1; // this is probably what we want
72 }
73 if (rc != ERROR_INVALID_HANDLE) {
74 return -1;
75 }
76 }
77
78 rc = WaitForMultipleObjects( 1,
79 &hFile,
80 TRUE, /* wait all */
81 msecs); /*millisecs*/
82
83 /* 1 => Input ready, 0 => not ready, -1 => error */
84 switch (rc) {
85 case WAIT_TIMEOUT: return 0;
86 case WAIT_OBJECT_0: return 1;
87 default: return -1;
88 }
89 }
90 #endif
91 }