fdio.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * fdio.c - safe file descriptor based input/output
  4. *
  5. * Copyright © 2009-2010 Guillem Jover <guillem@debian.org>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <compat.h>
  22. #include <errno.h>
  23. #include <unistd.h>
  24. #include <dpkg/fdio.h>
  25. ssize_t
  26. fd_read(int fd, void *buf, size_t len)
  27. {
  28. ssize_t total = 0;
  29. char *ptr = buf;
  30. while (len > 0) {
  31. ssize_t n;
  32. n = read(fd, ptr + total, len);
  33. if (n == -1) {
  34. if (errno == EINTR || errno == EAGAIN)
  35. continue;
  36. return total ? -total : n;
  37. }
  38. if (n == 0)
  39. break;
  40. total += n;
  41. len -= n;
  42. }
  43. return total;
  44. }
  45. ssize_t
  46. fd_write(int fd, const void *buf, size_t len)
  47. {
  48. ssize_t total = 0;
  49. const char *ptr = buf;
  50. while (len > 0) {
  51. ssize_t n;
  52. n = write(fd, ptr + total, len);
  53. if (n == -1) {
  54. if (errno == EINTR || errno == EAGAIN)
  55. continue;
  56. return total ? -total : n;
  57. }
  58. if (n == 0)
  59. break;
  60. total += n;
  61. len -= n;
  62. }
  63. return total;
  64. }