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