fd.cc 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include "fd.h"
  15. #include <unistd.h>
  16. #include <cerrno>
  17. namespace isc {
  18. namespace util {
  19. namespace io {
  20. bool
  21. write_data(const int fd, const void *buffer_v, const size_t length) {
  22. const unsigned char* buffer(static_cast<const unsigned char*>(buffer_v));
  23. size_t remaining = length; // Amount remaining to be written
  24. while (remaining > 0) {
  25. ssize_t amount = write(fd, buffer, remaining);
  26. if (amount == -1) {
  27. // Some error. Ignore interrupted system calls otherwise return
  28. // an error indication.
  29. if (errno != EINTR) {
  30. return false;
  31. }
  32. } else if (amount > 0) {
  33. // Wrote "amount" bytes from the buffer
  34. remaining -= amount;
  35. buffer += amount;
  36. } else {
  37. // Wrote zero bytes from the buffer. We should not get here as any
  38. // error that causes zero bytes to be written should have returned
  39. // -1. However, write(2) can return 0, and in this case we
  40. // interpret it as an error.
  41. return (false);
  42. }
  43. }
  44. return (true);
  45. }
  46. ssize_t
  47. read_data(const int fd, void *buffer_v, const size_t length) {
  48. unsigned char* buffer(static_cast<unsigned char*>(buffer_v));
  49. size_t remaining = length; // Amount remaining to be read
  50. while (remaining > 0) {
  51. ssize_t amount = read(fd, buffer, remaining);
  52. if (amount == -1) {
  53. // Some error. Ignore interrupted system calls otherwise return
  54. // an error indication.
  55. if (errno != EINTR) {
  56. return -1;
  57. }
  58. } else if (amount > 0) {
  59. // Read "amount" bytes into the buffer
  60. remaining -= amount;
  61. buffer += amount;
  62. } else {
  63. // EOF - end the read
  64. break;
  65. }
  66. }
  67. // Return total number of bytes read
  68. return (static_cast<ssize_t>(length - remaining));
  69. }
  70. }
  71. }
  72. }