forked from 54shady/linuxc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrap.c
More file actions
142 lines (117 loc) · 2.03 KB
/
Copy pathwrap.c
File metadata and controls
142 lines (117 loc) · 2.03 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
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
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include "wrap.h"
void perr_exit(const char *s)
{
perror(s);
exit(1);
}
int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
{
int afd;
again:
if ( (afd= accept(fd, sa, salenptr)) < 0)
{
if ( (errno == ECONNABORTED) || (errno == EINTR) )
goto again;
else
perr_exit("accept error");
}
return afd;
}
void Bind(int fd, struct sockaddr *sa, socklen_t salen)
{
if (bind(fd, sa, salen) < 0)
perr_exit("Bind error");
}
void Connect(int fd, struct sockaddr *sa, socklen_t salen)
{
if (connect(fd, sa, salen) < 0)
perr_exit("Connect error");
}
void Listen(int fd, int backlog)
{
if (listen(fd, backlog) < 0)
perr_exit("Listen error");
}
int Socket(int family, int type, int protocol)
{
int ret;
if ( (ret = socket(family, type, protocol)) < 0 )
perr_exit("Socket error");
return ret;
}
ssize_t Read(int fd, void *ptr, size_t nbytes)
{
ssize_t bytes;
again:
if ( (bytes = read(fd, ptr, nbytes)) == -1)
{
if (errno == EINTR)
goto again;
else
return bytes;
}
return bytes;
}
ssize_t Write(int fd, const void *ptr, size_t nbytes)
{
again:
if ( (nbytes = write(fd, ptr, nbytes)) == -1)
{
if (errno == EINTR)
goto again;
else
return nbytes;
}
return nbytes;
}
void Close(int fd)
{
if (close(fd) == -1)
perr_exit("Close error");
}
/* 读固定长度 */
ssize_t Readn(int fd, void *vptr, size_t nbytes)
{
size_t nleft;
ssize_t nread;
char *ptr;
ptr = vptr;
nleft = nbytes;
while (nleft > 0)
{
if ( (nread = read(fd, ptr, nleft)) < 0)
{
if (errno == EINTR)
nread = 0;
else
return -1;
}
nleft -= nread;
ptr += nread;
}
return nbytes - nleft;
}
ssize_t Writen(int fd, const void *vptr, size_t nbytes)
{
size_t nleft;
ssize_t nwritten;
const char *ptr;
ptr = vptr;
nleft = nbytes;
while (nleft > 0)
{
if ( (nwritten = write(fd, ptr, nleft)) <= 0)
{
if (nwritten < 0 && errno == EINTR)
nwritten = 0;
else
return -1;
}
nleft -= nwritten;
ptr += nwritten;
}
return nbytes;
}