Support non-blocking pipe I/O in write() on native Windows.
[gnulib.git] / lib / write.c
1 /* POSIX compatible write() function.
2    Copyright (C) 2008-2011 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2008.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU 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 General Public License for more details.
14
15    You should have received a copy of the GNU 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 /* Replace this function only if module 'nonblocking' or module 'sigpipe' is
24    requested.  */
25 #if GNULIB_NONBLOCKING || GNULIB_SIGPIPE
26
27 /* On native Windows platforms, SIGPIPE does not exist.  When write() is
28    called on a pipe with no readers, WriteFile() fails with error
29    GetLastError() = ERROR_NO_DATA, and write() in consequence fails with
30    error EINVAL.  */
31
32 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
33
34 #  include <errno.h>
35 #  include <signal.h>
36 #  include <io.h>
37
38 #  define WIN32_LEAN_AND_MEAN  /* avoid including junk */
39 #  include <windows.h>
40
41 ssize_t
42 rpl_write (int fd, const void *buf, size_t count)
43 #undef write
44 {
45   ssize_t ret = write (fd, buf, count);
46
47   if (ret < 0)
48     {
49 #  if GNULIB_NONBLOCKING
50       if (errno == ENOSPC)
51         {
52           HANDLE h = (HANDLE) _get_osfhandle (fd);
53           if (GetFileType (h) == FILE_TYPE_PIPE)
54             {
55               /* h is a pipe or socket.  */
56               DWORD state;
57               if (GetNamedPipeHandleState (h, &state, NULL, NULL, NULL, NULL, 0)
58                   && (state & PIPE_NOWAIT) != 0)
59                 /* h is a pipe in non-blocking mode.
60                    Change errno from ENOSPC to EAGAIN.  */
61                 errno = EAGAIN;
62             }
63         }
64       else
65 #  endif
66         {
67 #  if GNULIB_SIGPIPE
68           if (GetLastError () == ERROR_NO_DATA
69               && GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_PIPE)
70             {
71               /* Try to raise signal SIGPIPE.  */
72               raise (SIGPIPE);
73               /* If it is currently blocked or ignored, change errno from
74                  EINVAL to EPIPE.  */
75               errno = EPIPE;
76             }
77 #  endif
78         }
79     }
80   return ret;
81 }
82
83 # endif
84 #endif