5e01f8f75e31c5126eb99190cce5be382eb51ea5
[platform/upstream/bash.git] / lib / sh / input_avail.c
1 /* input_avail.c -- check whether or not data is available for reading on a
2                     specified file descriptor. */
3
4 /* Copyright (C) 2008,2009 Free Software Foundation, Inc.
5
6    This file is part of GNU Bash, the Bourne Again SHell.
7
8    Bash is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation, either version 3 of the License, or
11    (at your option) any later version.
12
13    Bash is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #if defined (__TANDEM)
23 #  include <floss.h>
24 #endif
25
26 #if defined (HAVE_CONFIG_H)
27 #  include <config.h>
28 #endif
29
30 #include <sys/types.h>
31 #include <fcntl.h>
32 #if defined (HAVE_SYS_FILE_H)
33 #  include <sys/file.h>
34 #endif /* HAVE_SYS_FILE_H */
35
36 #if defined (HAVE_UNISTD_H)
37 #  include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #include "bashansi.h"
41
42 #if defined (HAVE_SELECT)
43 #  if !defined (HAVE_SYS_SELECT_H) || !defined (M_UNIX)
44 #    include <sys/time.h>
45 #  endif
46 #endif /* HAVE_SELECT */
47 #if defined (HAVE_SYS_SELECT_H)
48 #  include <sys/select.h>
49 #endif
50
51 #if defined (FIONREAD_IN_SYS_IOCTL)
52 #  include <sys/ioctl.h>
53 #endif
54
55 #include <stdio.h>
56 #include <errno.h>
57
58 #if !defined (errno)
59 extern int errno;
60 #endif /* !errno */
61
62 #if !defined (O_NDELAY) && defined (O_NONBLOCK)
63 #  define O_NDELAY O_NONBLOCK   /* Posix style */
64 #endif
65
66 /* Return >= 1 if select/FIONREAD indicates data available for reading on
67    file descriptor FD; 0 if no data available.  Return -1 on error. */
68 int
69 input_avail (fd)
70      int fd;
71 {
72   int result, chars_avail;
73 #if defined(HAVE_SELECT)
74   fd_set readfds, exceptfds;
75   struct timeval timeout;
76 #endif
77
78   if (fd < 0)
79     return -1;
80
81   chars_avail = 0;
82
83 #if defined (HAVE_SELECT)
84   FD_ZERO (&readfds);
85   FD_ZERO (&exceptfds);
86   FD_SET (fd, &readfds);
87   FD_SET (fd, &exceptfds);
88   timeout.tv_sec = 0;
89   timeout.tv_usec = 0;
90   result = select (fd + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
91   return ((result <= 0) ? 0 : 1);
92
93 #endif
94
95   result = -1;
96 #if defined (FIONREAD)
97   errno = 0;
98   result = ioctl (fd, FIONREAD, &chars_avail);
99   if (result == -1 && errno == EIO)
100     return -1;
101   return (chars_avail);
102 #endif
103
104   return 0;
105 }