-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.c
89 lines (82 loc) · 1.55 KB
/
common.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
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "common.h"
void everror(const char *s) { // TODO
fprintf(stderr, "%s\n", s);
}
void printf_err(const char *format, ...) {
va_list arglist;
va_start(arglist, format);
vfprintf(stderr, format, arglist);
va_end(arglist);
fprintf(stderr, "\n");
}
int make_socket_nonblocking(int fd) {
int flags;
if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
return -1;
}
if (!(flags & O_NONBLOCK)) {
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
return -1;
}
}
return 0;
}
/* return:
< 0 -- -errno
= 0 -- read returned EAGAIN
> 0 -- read bytes
*/
ssize_t read_wrapper(int fd, void *buf, size_t count) {
ssize_t bytes = recv(fd, buf, count, 0);
if (bytes < 0) {
switch (errno) {
case EAGAIN:
#if EAGAIN != EWOULDBLOCK
case EWOULDBLOCK:
#endif
return 0;
case ECONNRESET:
return -errno;
default:
perror("recv");
return -errno;
}
} else if (bytes == 0) {
return -ECONNRESET;
} else {
return bytes;
}
}
/* return:
< 0 -- -errno
= 0 -- write returned EAGAIN
> 0 -- write bytes
*/
ssize_t write_wrapper(int fd, void *buf, size_t count) {
ssize_t bytes = send(fd, buf, count, MSG_NOSIGNAL);
if (bytes < 0) {
switch (errno) {
case EAGAIN:
#if EAGAIN != EWOULDBLOCK
case EWOULDBLOCK:
#endif
return 0;
case ECONNRESET:
return -errno;
default:
perror("send");
return -errno;
}
} else if (bytes == 0) {
return -ECONNRESET;
} else {
return bytes;
}
}