-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_writev.c
62 lines (50 loc) · 1.47 KB
/
my_writev.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
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
/* My implemention of the writev() system call.
* */
ssize_t my_writev(int fd, const struct iovec *iov, int iovcnt) {
int i;
int bytes_written;
for (i=0; i<iovcnt; i++) {
bytes_written = write(fd, iov[i].iov_base, iov[i].iov_len);
if ((bytes_written == -1) || (bytes_written != iov[i].iov_len)) {
return -1;
}
}
}
int main(int argc, char *argv[]) {
char str1[] = "First line of the file\n";
char str2[] = "Second line of the file\n";
int num1 = 77;
float num2 = 7.7;
struct iovec iovector[4];
iovector[0].iov_base = str1;
iovector[0].iov_len = strlen(str1);
iovector[1].iov_base = str2;
iovector[1].iov_len = strlen(str2);
iovector[2].iov_base = &num1;
iovector[2].iov_len = sizeof(int);
iovector[3].iov_base = &num2;
iovector[3].iov_len = sizeof(float);
int fptr = open("/dev/fd/1", O_WRONLY);
if (fptr == -1) {
errExit("open(stdout, O_WRONLY)");
}
if (my_writev(fptr, &iovector[0], 4) == -1) {
fprintf(stderr, "Error in my_writev()");
close(fptr);
exit(EXIT_FAILURE);
}
if (close(fptr) == -1) {
errExit("close(fptr)");
}
return EXIT_SUCCESS;
}