copy_fd(): do not close the input file descriptor

The caller, not this function, opened the file descriptor; it is selfish for the callee to close it when it is done reading from it. The caller may want an option to rewind and re-read the contents after it returns. Simplify the loop to copy the input in full to the output; its body essentially is what a call to write_in_full() helper does. Signed-off-by: Steffen Prohaska <prohaska@zib.de> Helped-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Steffen Prohaska committed Aug 26, 2014 at 17:23 UTC b29763aa9bcbb99a59aec3820e30ff1864cfa765
2 files changed +8 -21
copy.c
+5 -21
@@ -4,34 +4,17 @@ int copy_fd(int ifd, int ofd)
4 {
5 while (1) {
6 char buffer[8192];
7 - char *buf = buffer;
7 ssize_t len = xread(ifd, buffer, sizeof(buffer));
8 if (!len)
9 break;
10 if (len < 0) {
12 - int read_error = errno;
13 - close(ifd);
11 return error("copy-fd: read returned %s",
15 - strerror(read_error));
16 - }
17 - while (len) {
18 - int written = xwrite(ofd, buf, len);
19 - if (written > 0) {
20 - buf += written;
21 - len -= written;
22 - }
23 - else if (!written) {
24 - close(ifd);
25 - return error("copy-fd: write returned 0");
26 - } else {
27 - int write_error = errno;
28 - close(ifd);
29 - return error("copy-fd: write returned %s",
30 - strerror(write_error));
31 - }
12 + strerror(errno));
13 }
14 + if (write_in_full(ofd, buffer, len) < 0)
15 + return error("copy-fd: write returned %s",
16 + strerror(errno));
17 }
34 - close(ifd);
18 return 0;
19 }
20
@@ -60,6 +43,7 @@ int copy_file(const char *dst, const char *src, int mode)
43 return fdo;
44 }
45 status = copy_fd(fdi, fdo);
46 + close(fdi);
47 if (close(fdo) != 0)
48 return error("%s: close error: %s", dst, strerror(errno));
49
lockfile.c
+3
@@ -224,8 +224,11 @@ int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
224 } else if (copy_fd(orig_fd, fd)) {
225 if (flags & LOCK_DIE_ON_ERROR)
226 exit(128);
227 + close(orig_fd);
228 close(fd);
229 return -1;
230 + } else {
231 + close(orig_fd);
232 }
233 return fd;
234 }