safe-read.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* An interface to read and write that retries after interrupts.
  2. Copyright (C) 1993, 1994, 1998, 2002-2003 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software Foundation,
  13. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  14. #if HAVE_CONFIG_H
  15. # include <config.h>
  16. #endif
  17. /* Specification. */
  18. #ifdef SAFE_WRITE
  19. # include "safe-write.h"
  20. #else
  21. # include "safe-read.h"
  22. #endif
  23. /* Get ssize_t. */
  24. #include <sys/types.h>
  25. #if HAVE_UNISTD_H
  26. # include <unistd.h>
  27. #endif
  28. #include <errno.h>
  29. #ifndef errno
  30. extern int errno;
  31. #endif
  32. #ifdef EINTR
  33. # define IS_EINTR(x) ((x) == EINTR)
  34. #else
  35. # define IS_EINTR(x) 0
  36. #endif
  37. #include <limits.h>
  38. #ifdef SAFE_WRITE
  39. # define safe_rw safe_write
  40. # define rw write
  41. #else
  42. # define safe_rw safe_read
  43. # define rw read
  44. # undef const
  45. # define const /* empty */
  46. #endif
  47. /* Read(write) up to COUNT bytes at BUF from(to) descriptor FD, retrying if
  48. interrupted. Return the actual number of bytes read(written), zero for EOF,
  49. or SAFE_READ_ERROR(SAFE_WRITE_ERROR) upon error. */
  50. size_t
  51. safe_rw (int fd, void const *buf, size_t count)
  52. {
  53. ssize_t result;
  54. /* POSIX limits COUNT to SSIZE_MAX, but we limit it further, requiring
  55. that COUNT <= INT_MAX, to avoid triggering a bug in Tru64 5.1.
  56. When decreasing COUNT, keep the file pointer block-aligned.
  57. Note that in any case, read(write) may succeed, yet read(write)
  58. fewer than COUNT bytes, so the caller must be prepared to handle
  59. partial results. */
  60. if (count > INT_MAX)
  61. count = INT_MAX & ~8191;
  62. do
  63. {
  64. result = rw (fd, buf, count);
  65. }
  66. while (result < 0 && IS_EINTR (errno));
  67. return (size_t) result;
  68. }