-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathfd.c
More file actions
55 lines (48 loc) · 1.14 KB
/
Copy pathfd.c
File metadata and controls
55 lines (48 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include <unistd.h>
#include "fd.h"
/* Robust full-buffer write loop. Restarts on EINTR; treats a
* short-write of 0 as an error. Shared by every persistence format
* trinity emits so the loop lives in one place instead of being
* copy-pasted with no semantic divergence between callers. */
ssize_t write_all(int fd, const void *buf, size_t len)
{
const uint8_t *p = buf;
size_t left = len;
while (left > 0) {
ssize_t n = write(fd, p, left);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (n == 0)
return -1;
p += n;
left -= n;
}
return (ssize_t)len;
}
/* Robust full-buffer read loop. Restarts on EINTR; returns the number
* of bytes successfully read, which may be less than @len at EOF.
* Counterpart to write_all() and shared by the same callers. */
ssize_t read_all(int fd, void *buf, size_t len)
{
uint8_t *p = buf;
size_t left = len;
while (left > 0) {
ssize_t n = read(fd, p, left);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (n == 0)
break;
p += n;
left -= n;
}
return (ssize_t)(len - left);
}