3
0

copyfd.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include <errno.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include "libbb.h"
  14. #if BUFSIZ < 4096
  15. #undef BUFSIZ
  16. #define BUFSIZ 4096
  17. #endif
  18. static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
  19. {
  20. int status = -1;
  21. off_t total = 0;
  22. RESERVE_CONFIG_BUFFER(buffer, BUFSIZ);
  23. if (src_fd < 0) goto out;
  24. if (!size) {
  25. size = BUFSIZ;
  26. status = 1; /* copy until eof */
  27. }
  28. while (1) {
  29. ssize_t rd;
  30. rd = safe_read(src_fd, buffer, size > BUFSIZ ? BUFSIZ : size);
  31. if (!rd) { /* eof - all done. */
  32. status = 0;
  33. break;
  34. }
  35. if (rd < 0) {
  36. bb_perror_msg(bb_msg_read_error);
  37. break;
  38. }
  39. /* dst_fd == -1 is a fake, else... */
  40. if (dst_fd >= 0) {
  41. ssize_t wr = full_write(dst_fd, buffer, rd);
  42. if (wr < rd) {
  43. bb_perror_msg(bb_msg_write_error);
  44. break;
  45. }
  46. }
  47. total += rd;
  48. if (status < 0) {
  49. size -= rd;
  50. if (!size) {
  51. status = 0;
  52. break;
  53. }
  54. }
  55. }
  56. out:
  57. RELEASE_CONFIG_BUFFER(buffer);
  58. return status ? -1 : total;
  59. }
  60. off_t bb_copyfd_size(int fd1, int fd2, off_t size)
  61. {
  62. if (size) {
  63. return bb_full_fd_action(fd1, fd2, size);
  64. }
  65. return 0;
  66. }
  67. off_t bb_copyfd_eof(int fd1, int fd2)
  68. {
  69. return bb_full_fd_action(fd1, fd2, 0);
  70. }