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
|
#include "asm/unistd_64.h" // for __NR_writev
#include <errno.h> // for errno, EAGAIN, EINTR, EINVAL
#include <string.h> // for memcpy
#include <sys/types.h> // for ssize_t, size_t
#include <syscall.h> // for __syscall_3, syscall
#include <linux/uio.h> // for iovec, UIO_MAXIOV
ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
{
ssize_t total = 0;
if (iovcnt < 0) {
errno = EINVAL;
return -1;
}
while (iovcnt > 0) {
int chunk = iovcnt > UIO_MAXIOV ? UIO_MAXIOV : iovcnt;
struct iovec local[UIO_MAXIOV];
memcpy(local, iov, chunk * sizeof(struct iovec));
ssize_t ret = syscall(writev, fd, local, chunk);
if (ret < 0) {
if (total > 0 && (errno == EAGAIN || errno == EINTR))
return total;
return ret;
}
total += ret;
ssize_t remaining = ret;
while (remaining > 0 && iovcnt > 0) {
if ((size_t)remaining >= iov->iov_len) {
remaining -= iov->iov_len;
iov++;
iovcnt--;
} else {
struct iovec tmp = *iov;
tmp.iov_base = (char *)tmp.iov_base + remaining;
tmp.iov_len -= remaining;
memcpy(local, &tmp, sizeof(tmp));
break;
}
}
}
return total;
}
|