safe-read.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* An interface to read and write that retries after interrupts.
  2. Copyright (C) 1993, 1994, 1998, 2002, 2003, 2004, 2005 Free Software
  3. Foundation, Inc.
  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 2, or (at your option)
  7. 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, write to the Free Software Foundation,
  14. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  15. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. /* Specification. */
  19. #ifdef SAFE_WRITE
  20. # include "safe-write.h"
  21. #else
  22. # include "safe-read.h"
  23. #endif
  24. /* Get ssize_t. */
  25. #include <sys/types.h>
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #ifdef EINTR
  29. # define IS_EINTR(x) ((x) == EINTR)
  30. #else
  31. # define IS_EINTR(x) 0
  32. #endif
  33. #include <limits.h>
  34. #ifdef SAFE_WRITE
  35. # define safe_rw safe_write
  36. # define rw write
  37. #else
  38. # define safe_rw safe_read
  39. # define rw read
  40. # undef const
  41. # define const /* empty */
  42. #endif
  43. /* Read(write) up to COUNT bytes at BUF from(to) descriptor FD, retrying if
  44. interrupted. Return the actual number of bytes read(written), zero for EOF,
  45. or SAFE_READ_ERROR(SAFE_WRITE_ERROR) upon error. */
  46. size_t
  47. safe_rw (int fd, void const *buf, size_t count)
  48. {
  49. /* Work around a bug in Tru64 5.1. Attempting to read more than
  50. INT_MAX bytes fails with errno == EINVAL. See
  51. <http://lists.gnu.org/archive/html/bug-gnu-utils/2002-04/msg00010.html>.
  52. When decreasing COUNT, keep it block-aligned. */
  53. enum { BUGGY_READ_MAXIMUM = INT_MAX & ~8191 };
  54. for (;;)
  55. {
  56. ssize_t result = rw (fd, buf, count);
  57. if (0 <= result)
  58. return result;
  59. else if (IS_EINTR (errno))
  60. continue;
  61. else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count)
  62. count = BUGGY_READ_MAXIMUM;
  63. else
  64. return result;
  65. }
  66. }