write.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* POSIX compatible write() function.
  2. Copyright (C) 2008-2010 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2008.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <unistd.h>
  17. /* Replace this function only if module 'sigpipe' is requested. */
  18. #if GNULIB_SIGPIPE
  19. /* On native Windows platforms, SIGPIPE does not exist. When write() is
  20. called on a pipe with no readers, WriteFile() fails with error
  21. GetLastError() = ERROR_NO_DATA, and write() in consequence fails with
  22. error EINVAL. */
  23. # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  24. # include <errno.h>
  25. # include <signal.h>
  26. # include <io.h>
  27. # define WIN32_LEAN_AND_MEAN /* avoid including junk */
  28. # include <windows.h>
  29. ssize_t
  30. rpl_write (int fd, const void *buf, size_t count)
  31. #undef write
  32. {
  33. ssize_t ret = write (fd, buf, count);
  34. if (ret < 0)
  35. {
  36. if (GetLastError () == ERROR_NO_DATA
  37. && GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_PIPE)
  38. {
  39. /* Try to raise signal SIGPIPE. */
  40. raise (SIGPIPE);
  41. /* If it is currently blocked or ignored, change errno from EINVAL
  42. to EPIPE. */
  43. errno = EPIPE;
  44. }
  45. }
  46. return ret;
  47. }
  48. # endif
  49. #endif