Gentoo Archives: gentoo-commits

From: Mike Frysinger <vapier@g.o>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/portage-utils:master commit in: libq/
Date: Thu, 29 Dec 2016 02:25:56
Message-Id: 1482963265.2863e563f7b37d9e9cbb56551c8a4c033f802750.vapier@gentoo
1 commit: 2863e563f7b37d9e9cbb56551c8a4c033f802750
2 Author: Mike Frysinger <vapier <AT> gentoo <DOT> org>
3 AuthorDate: Wed Dec 28 22:14:25 2016 +0000
4 Commit: Mike Frysinger <vapier <AT> gentoo <DOT> org>
5 CommitDate: Wed Dec 28 22:14:25 2016 +0000
6 URL: https://gitweb.gentoo.org/proj/portage-utils.git/commit/?id=2863e563
7
8 copy_file: rewrite to use fds
9
10 This avoids FILE* leakage and produces a little bit smaller code.
11
12 libq/copy_file.c | 63 ++++++++++++++++++++++++++++++++++++--------------------
13 1 file changed, 41 insertions(+), 22 deletions(-)
14
15 diff --git a/libq/copy_file.c b/libq/copy_file.c
16 index ee1338d..4230b73 100644
17 --- a/libq/copy_file.c
18 +++ b/libq/copy_file.c
19 @@ -1,31 +1,50 @@
20 -static int copy_file_fd(int fd_src, int fd_dst)
21 +static ssize_t safe_read(int fd, void *buf, size_t len)
22 {
23 - FILE *fp_src, *fp_dst;
24 - size_t rcnt, wcnt;
25 - char buf[BUFSIZE];
26 + ssize_t ret;
27
28 - /* dont fclose() as that implicitly close()'s */
29 + while (1) {
30 + ret = read(fd, buf, len);
31 + if (ret >= 0)
32 + break;
33 + else if (errno != EINTR)
34 + break;
35 + }
36
37 - fp_src = fdopen(fd_src, "r");
38 - if (!fp_src)
39 - return -1;
40 + return ret;
41 +}
42
43 - fp_dst = fdopen(fd_dst, "w");
44 - if (!fp_dst)
45 - return -1;
46 +static ssize_t safe_write(int fd, const void *buf, size_t len)
47 +{
48 + ssize_t ret;
49
50 - while (1) {
51 - rcnt = fread(buf, sizeof(buf[0]), sizeof(buf), fp_src);
52 - if (!rcnt) {
53 - fflush(fp_dst);
54 - return feof(fp_src) ? 0 : -1;
55 + while (len) {
56 + ret = write(fd, buf, len);
57 + if (ret < 0) {
58 + if (errno == EINTR)
59 + continue;
60 + return -1;
61 }
62 + buf += ret;
63 + len -= ret;
64 + }
65
66 - wcnt = fwrite(buf, sizeof(buf[0]), rcnt, fp_dst);
67 - if (wcnt != rcnt) {
68 - if (ferror(fp_dst))
69 - return -1;
70 - fseek(fp_src, wcnt - rcnt, SEEK_CUR);
71 - }
72 + return ret;
73 +}
74 +
75 +static int copy_file_fd(int fd_src, int fd_dst)
76 +{
77 + ssize_t rcnt, wcnt;
78 + char buf[64 * 1024];
79 +
80 + while (1) {
81 + rcnt = safe_read(fd_src, buf, sizeof(buf));
82 + if (rcnt < 0)
83 + return -1;
84 + else if (rcnt == 0)
85 + return 0;
86 +
87 + wcnt = safe_write(fd_dst, buf, rcnt);
88 + if (wcnt == -1)
89 + return -1;
90 }
91 }