Update Gnulib to v0.0-6827-g39c3009; use the `dirfd' module.
[bpt/guile.git] / lib / read.c
1 /* POSIX compatible read() function.
2 Copyright (C) 2008-2012 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2011.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 /* Specification. */
21 #include <unistd.h>
22
23 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
24
25 # include <errno.h>
26 # include <io.h>
27
28 # define WIN32_LEAN_AND_MEAN /* avoid including junk */
29 # include <windows.h>
30
31 # include "msvc-inval.h"
32 # include "msvc-nothrow.h"
33
34 # undef read
35
36 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
37 static inline ssize_t
38 read_nothrow (int fd, void *buf, size_t count)
39 {
40 ssize_t result;
41
42 TRY_MSVC_INVAL
43 {
44 result = read (fd, buf, count);
45 }
46 CATCH_MSVC_INVAL
47 {
48 result = -1;
49 errno = EBADF;
50 }
51 DONE_MSVC_INVAL;
52
53 return result;
54 }
55 # else
56 # define read_nothrow read
57 # endif
58
59 ssize_t
60 rpl_read (int fd, void *buf, size_t count)
61 {
62 ssize_t ret = read_nothrow (fd, buf, count);
63
64 # if GNULIB_NONBLOCKING
65 if (ret < 0
66 && GetLastError () == ERROR_NO_DATA)
67 {
68 HANDLE h = (HANDLE) _get_osfhandle (fd);
69 if (GetFileType (h) == FILE_TYPE_PIPE)
70 {
71 /* h is a pipe or socket. */
72 DWORD state;
73 if (GetNamedPipeHandleState (h, &state, NULL, NULL, NULL, NULL, 0)
74 && (state & PIPE_NOWAIT) != 0)
75 /* h is a pipe in non-blocking mode.
76 Change errno from EINVAL to EAGAIN. */
77 errno = EAGAIN;
78 }
79 }
80 # endif
81
82 return ret;
83 }
84
85 #endif