ioall.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * The Qubes OS Project, http://www.qubes-os.org
  3. *
  4. * Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. *
  20. */
  21. #include <unistd.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <fcntl.h>
  25. #include <errno.h>
  26. void perror_wrapper(char * msg)
  27. {
  28. int prev=errno;
  29. perror(msg);
  30. errno=prev;
  31. }
  32. int write_all(int fd, void *buf, int size)
  33. {
  34. int written = 0;
  35. int ret;
  36. while (written < size) {
  37. ret = write(fd, (char *) buf + written, size - written);
  38. if (ret == -1 && errno == EINTR)
  39. continue;
  40. if (ret <= 0) {
  41. perror_wrapper("write");
  42. return 0;
  43. }
  44. written += ret;
  45. }
  46. // fprintf(stderr, "sent %d bytes\n", size);
  47. return 1;
  48. }
  49. int read_all(int fd, void *buf, int size)
  50. {
  51. int got_read = 0;
  52. int ret;
  53. while (got_read < size) {
  54. ret = read(fd, (char *) buf + got_read, size - got_read);
  55. if (ret == -1 && errno == EINTR)
  56. continue;
  57. if (ret == 0) {
  58. errno = 0;
  59. fprintf(stderr, "EOF\n");
  60. return 0;
  61. }
  62. if (ret < 0) {
  63. perror_wrapper("read");
  64. return 0;
  65. }
  66. got_read += ret;
  67. }
  68. // fprintf(stderr, "read %d bytes\n", size);
  69. return 1;
  70. }
  71. int copy_fd_all(int fdout, int fdin)
  72. {
  73. int ret;
  74. char buf[4096];
  75. for (;;) {
  76. ret = read(fdin, buf, sizeof(buf));
  77. if (ret == -1 && errno == EINTR)
  78. continue;
  79. if (!ret)
  80. break;
  81. if (ret < 0) {
  82. perror_wrapper("read");
  83. return 0;
  84. }
  85. if (!write_all(fdout, buf, ret)) {
  86. perror_wrapper("write");
  87. return 0;
  88. }
  89. }
  90. return 1;
  91. }