fsck: exit with non-zero status upon errors
[git] / write_or_die.c
1 #include "cache.h"
2
3 int read_in_full(int fd, void *buf, size_t count)
4 {
5         char *p = buf;
6         ssize_t total = 0;
7
8         while (count > 0) {
9                 ssize_t loaded = xread(fd, p, count);
10                 if (loaded <= 0)
11                         return total ? total : loaded;
12                 count -= loaded;
13                 p += loaded;
14                 total += loaded;
15         }
16
17         return total;
18 }
19
20 int write_in_full(int fd, const void *buf, size_t count)
21 {
22         const char *p = buf;
23         ssize_t total = 0;
24
25         while (count > 0) {
26                 ssize_t written = xwrite(fd, p, count);
27                 if (written < 0)
28                         return -1;
29                 if (!written) {
30                         errno = ENOSPC;
31                         return -1;
32                 }
33                 count -= written;
34                 p += written;
35                 total += written;
36         }
37
38         return total;
39 }
40
41 void write_or_die(int fd, const void *buf, size_t count)
42 {
43         if (write_in_full(fd, buf, count) < 0) {
44                 if (errno == EPIPE)
45                         exit(0);
46                 die("write error (%s)", strerror(errno));
47         }
48 }
49
50 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
51 {
52         if (write_in_full(fd, buf, count) < 0) {
53                 if (errno == EPIPE)
54                         exit(0);
55                 fprintf(stderr, "%s: write error (%s)\n",
56                         msg, strerror(errno));
57                 return 0;
58         }
59
60         return 1;
61 }
62
63 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
64 {
65         if (write_in_full(fd, buf, count) < 0) {
66                 fprintf(stderr, "%s: write error (%s)\n",
67                         msg, strerror(errno));
68                 return 0;
69         }
70
71         return 1;
72 }