fd.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (C) 2010 CZ NIC
  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 char *buffer, const size_t length) {
  22. size_t rest(length);
  23. // Just keep writing until all is written
  24. while (rest) {
  25. ssize_t written(write(fd, buffer, rest));
  26. if (rest == -1) {
  27. if (errno == EINTR) { // Just keep going
  28. continue;
  29. } else {
  30. return false;
  31. }
  32. } else { // Wrote something
  33. rest -= written;
  34. buffer += written;
  35. }
  36. }
  37. return true;
  38. }
  39. ssize_t
  40. read_data(const int fd, char *buffer, const size_t length) {
  41. size_t rest(length), already(0);
  42. while (rest) { // Stil something to read
  43. ssize_t amount(read(fd, buffer, rest));
  44. if (rest == -1) {
  45. if (errno == EINTR) { // Continue on interrupted call
  46. continue;
  47. } else {
  48. return -1;
  49. }
  50. } else if (amount) {
  51. already += amount;
  52. rest -= amount;
  53. buffer += amount;
  54. } else { // EOF
  55. return already;
  56. }
  57. }
  58. return already;
  59. }
  60. }
  61. }
  62. }