-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
110 lines (96 loc) · 4.29 KB
/
util.c
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include "util.h"
#define ATOMIC_IO(func, fd, buf, count, hup) do { \
ssize_t nbytes_tot = 0; \
ssize_t nbytes_cur = 0; \
uint8_t done = 0; \
\
while (!done) { \
nbytes_cur = (func)((fd), (buf) + nbytes_tot, count - nbytes_tot); \
if (-1 == nbytes_cur) { \
switch (errno) { \
case EAGAIN: \
done = 1; \
break; \
case EINTR: \
break; \
case EPIPE: \
if (NULL != hup) { \
*(hup) = 1; \
} \
done = 1; \
break; \
case ECONNRESET: \
if (NULL != hup) { \
*(hup) = 1; \
} \
done = 1; \
break; \
default: \
perrorf("atomic_io(fd=%d)", fd); \
abort(); \
break; \
} \
} else if (0 == nbytes_cur) { \
if (NULL != hup) { \
*(hup) = 1; \
} \
done = 1; \
} else { \
nbytes_tot += nbytes_cur; \
done = (nbytes_tot == count); \
} \
} \
return nbytes_tot; \
} while (0);
ssize_t atomic_read(int fd, void *buf, size_t count, uint8_t *hup) {
ATOMIC_IO(read, fd, buf, count, hup);
}
ssize_t atomic_write(int fd, const void *buf, size_t count, uint8_t *hup) {
ATOMIC_IO(write, fd, buf, count, hup);
}
void set_nonblocking(int fd) {
int flags = 0;
flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perrorf("fcntl(fd=%d)", fd);
abort();
}
if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK)) {
perrorf("fcntl(fd=%d)", fd);
abort();
}
}
void perrorf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, " %s\n", strerror(errno));
}
void checked_lock(pthread_mutex_t *lock) {
assert(NULL != lock);
if (-1 == pthread_mutex_lock(lock)) {
perror("pthread_mutex_lock");
abort();
}
}
void checked_unlock(pthread_mutex_t *lock) {
assert(NULL != lock);
if (-1 == pthread_mutex_unlock(lock)) {
perror("pthread_mutex_unlock");
abort();
}
}