Skip to content

Commit b29763a

Browse files
sprohaskagitster
authored andcommitted
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 <[email protected]> Helped-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 0271022 commit b29763a

File tree

2 files changed

+8
-21
lines changed

2 files changed

+8
-21
lines changed

copy.c

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,17 @@ int copy_fd(int ifd, int ofd)
44
{
55
while (1) {
66
char buffer[8192];
7-
char *buf = buffer;
87
ssize_t len = xread(ifd, buffer, sizeof(buffer));
98
if (!len)
109
break;
1110
if (len < 0) {
12-
int read_error = errno;
13-
close(ifd);
1411
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));
3213
}
14+
if (write_in_full(ofd, buffer, len) < 0)
15+
return error("copy-fd: write returned %s",
16+
strerror(errno));
3317
}
34-
close(ifd);
3518
return 0;
3619
}
3720

@@ -60,6 +43,7 @@ int copy_file(const char *dst, const char *src, int mode)
6043
return fdo;
6144
}
6245
status = copy_fd(fdi, fdo);
46+
close(fdi);
6347
if (close(fdo) != 0)
6448
return error("%s: close error: %s", dst, strerror(errno));
6549

lockfile.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,11 @@ int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
224224
} else if (copy_fd(orig_fd, fd)) {
225225
if (flags & LOCK_DIE_ON_ERROR)
226226
exit(128);
227+
close(orig_fd);
227228
close(fd);
228229
return -1;
230+
} else {
231+
close(orig_fd);
229232
}
230233
return fd;
231234
}

0 commit comments

Comments
 (0)