-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiov.c
73 lines (56 loc) · 1.2 KB
/
iov.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include "iov.h"
void
initialize_iov(iov_t * iovec, size_t len)
{
if (!iovec) {
fprintf(stderr, "iovec is not initialized");
exit(1);
}
if (iovec->buf)
free(iovec->buf);
if (!(iovec->buf = malloc(len))) {
fprintf(stderr, "Out of memory: %s", strerror(errno));
exit(1);
}
iovec->to_read = len;
iovec->offset = 0;
}
void
reset_iov(iov_t * iovec)
{
if (iovec->buf)
free(iovec->buf);
iovec->buf = NULL;
iovec->to_read = 0;
iovec->offset = 0;
}
int
read_iov(iov_t * iovec, int sock)
{
int bytes_read;
bytes_read = recv(sock, &iovec->buf[iovec->offset], iovec->to_read, 0);
if (bytes_read <= 0)
return -1;
iovec->offset += bytes_read;
iovec->to_read -= bytes_read;
return iovec->to_read;
}
int
write_iov(iov_t * iovec, int sock)
{
int bytes_written;
bytes_written = send(sock,
&iovec->buf[iovec->offset], iovec->to_read,
MSG_NOSIGNAL);
if (bytes_written <= 0)
return -1;
iovec->offset += bytes_written;
iovec->to_read -= bytes_written;
return iovec->to_read;
}