xref: /openbsd/regress/sys/kern/pwritev/pwritev.c (revision 5af055cd)
1 /*	$OpenBSD: pwritev.c,v 1.5 2011/11/06 15:00:34 guenther Exp $	*/
2 /*
3  *	Written by Artur Grabowski <art@openbsd.org> 2002 Public Domain.
4  */
5 #include <sys/types.h>
6 #include <sys/uio.h>
7 #include <err.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <limits.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 
16 int
17 main(int argc, char *argv[])
18 {
19 	char temp[] = "/tmp/pwritevXXXXXXXXX";
20 	char magic[10] = "0123456789";
21 	const char zeroes[10] = "0000000000";
22 	char buf[10];
23 	struct iovec iov[2];
24 	char c;
25 	int fd, ret;
26 
27 	if ((fd = mkstemp(temp)) < 0)
28 		err(1, "mkstemp");
29 	remove(temp);
30 
31 	if (write(fd, zeroes, sizeof(zeroes)) != sizeof(zeroes))
32 		err(1, "write");
33 
34 	if (lseek(fd, 5, SEEK_SET) != 5)
35 		err(1, "lseek");
36 
37 	iov[0].iov_base = &magic[8];
38 	iov[0].iov_len = 2;
39 	iov[1].iov_base = &magic[7];
40 	iov[1].iov_len = 2;
41 
42 	if (pwritev(fd, iov, 2, 4) != 4)
43 		err(1, "pwritev");
44 
45 	if (read(fd, &c, 1) != 1)
46 		err(1, "read");
47 
48 	if (c != '9')
49 		errx(1, "read %c != %c", c, '9');
50 
51 	c = '5';
52 	if (write(fd, &c, 1) != 1)
53 		err(1, "write");
54 
55 	if (pread(fd, buf, 10, 0) != 10)
56 		err(1, "pread");
57 
58 	iov[1].iov_base = &magic[1];
59 	iov[1].iov_len = 2;
60 	if ((ret = pwritev(fd, iov, 2, -1)) != -1)
61 		errx(1, "pwritev with negative offset succeeded,\
62 				returning %d", ret);
63 	if (errno != EINVAL)
64 		err(1, "pwritev with negative offset");
65 
66 	if ((ret = pwritev(fd, iov, 2, LLONG_MAX)) != -1)
67 		errx(1, "pwritev with wrapping offset succeeded,\
68 				returning %d", ret);
69 	if (errno != EFBIG && errno != EINVAL)
70 		err(1, "pwritev with wrapping offset");
71 
72 	if (memcmp(buf, "0000895800", 10) != 0)
73 		errx(1, "data mismatch: %s != %s", buf, "0000895800");
74 
75 	/* pwrite should be unaffected by O_APPEND */
76 	if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_APPEND))
77 		err(1, "fcntl");
78 	if (pwritev(fd, iov, 2, 2) != 4)
79 		err(1, "pwritev");
80 	if (pread(fd, buf, 10, 0) != 10)
81 		err(1, "pread");
82 	if (memcmp(buf, "0089125800", 10) != 0)
83 		errx(1, "data mismatch: %s != %s", buf, "0089125800");
84 
85 	close(fd);
86 
87 	/* also, verify that pwritev fails on ttys */
88 	fd = open("/dev/tty", O_RDWR);
89 	if (fd < 0)
90 		printf("skipping tty test\n");
91 	else if ((ret = pwritev(fd, iov, 2, 7)) != -1)
92 		errx(1, "pwritev succeeded on tty, returning %d", ret);
93 	else if (errno != ESPIPE)
94 		err(1, "pwritev");
95 
96 	return 0;
97 }
98