-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.h
161 lines (123 loc) · 2.42 KB
/
common.h
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#ifndef COMMON_H
#define COMMON_H
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static inline void error(const char *msg)
{
perror(msg);
raise(SIGTERM);
}
static inline int max3(int a, int b, int c)
{
int m = a;
(m < b) && (m = b);
(m < c) && (m = c);
return m;
}
static inline int make_non_blocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
if(flags < 0) {
return flags;
}
flags |= O_NONBLOCK;
return fcntl(fd, F_SETFL, flags);
}
static inline int wait_all(int pid, int *status)
{
while (true) {
int status;
int result = waitpid(-1, &status, 0);
if (result < 0) {
if (errno == EINTR) {
continue;
}
return result;
}
if (WIFSTOPPED(status)) {
continue;
}
if (pid == result) {
break;
}
}
return 0;
}
static inline int write_all(int fd, const char *buf, size_t count)
{
size_t offset = 0;
while (offset < count) {
ssize_t length = write(fd, buf + offset, count - offset);
if (length < 0) {
if (errno == EINTR) {
continue;
}
if (errno == EWOULDBLOCK) {
continue; // We don't ever want the write side non-blocking!
}
if (errno == EIO && isatty(fd)) {
return offset;
}
if (offset > 0) {
return offset;
}
return length;
}
offset += length;
}
assert(offset == count);
return offset;
}
static inline int read_all(int fd, char *buf, size_t count)
{
size_t offset = 0;
while (offset < count) {
ssize_t length = read(fd, buf + offset, count - offset);
if (length < 0) {
if (errno == EINTR) {
continue;
}
if (errno == EWOULDBLOCK) {
return offset;
}
if (errno == EIO && isatty(fd)) {
return offset;
}
if (offset > 0) {
return offset;
}
return length;
}
if (length == 0) {
return offset;
}
offset += length;
}
assert(offset == count);
return offset;
}
static inline int read_then_write(int infd, int outfd, int bufsize)
{
char buffer[bufsize];
int n = read_all(infd, buffer, bufsize);
if (n < 0) {
return n;
}
if (n == 0) {
return n;
}
n = write_all(outfd, buffer, n);
if (n < 0) {
return n;
}
return n;
}
#endif // COMMON_H