xref: /openbsd/regress/sys/kern/pread/pread.c (revision 09467b48)
1 /*	$OpenBSD: pread.c,v 1.4 2011/11/06 15:00:34 guenther 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 <unistd.h>
12 
13 int
14 main(int argc, char *argv[])
15 {
16 	char temp[] = "/tmp/dup2XXXXXXXXX";
17 	const char magic[10] = "0123456789";
18 	char c;
19 	int fd, ret;
20 
21 	if ((fd = mkstemp(temp)) < 0)
22 		err(1, "mkstemp");
23 	remove(temp);
24 
25 	if (write(fd, magic, sizeof(magic)) != sizeof(magic))
26 		err(1, "write");
27 
28 	if (lseek(fd, 0, SEEK_SET) != 0)
29 		err(1, "lseek");
30 
31 	if (read(fd, &c, 1) != 1)
32 		err(1, "read1");
33 
34 	if (c != magic[0])
35 		errx(1, "read1 %c != %c", c, magic[0]);
36 
37 	if (pread(fd, &c, 1, 7) != 1)
38 		err(1, "pread");
39 
40 	if (c != magic[7])
41 		errx(1, "pread %c != %c", c, magic[7]);
42 
43 	if (read(fd, &c, 1) != 1)
44 		err(1, "read2");
45 
46 	if (c != magic[1])
47 		errx(1, "read2 %c != %c", c, magic[1]);
48 
49 	if ((ret = pread(fd, &c, 1, -1)) != -1)
50 		errx(1, "pread with negative offset succeeded,\
51 				returning %d", ret);
52 	if (errno != EINVAL)
53 		err(1, "pread with negative offset");
54 
55 	if ((ret = pread(fd, &c, 3, LLONG_MAX)) != -1)
56 		errx(1, "pread with wrapping offset succeeded,\
57 				returning %d", ret);
58 	if (errno != EINVAL)
59 		err(1, "pread with wrapping offset");
60 
61 	if (read(fd, &c, 1) != 1)
62 		err(1, "read3");
63 
64 	if (c != magic[2])
65 		errx(1, "read3 %c != %c", c, magic[2]);
66 
67 	close(fd);
68 
69 	/* also, verify that pread fails on ttys */
70 	fd = open("/dev/tty", O_RDWR);
71 	if (fd < 0)
72 		printf("skipping tty test\n");
73 	else if ((ret = pread(fd, &c, 1, 7)) != -1)
74 		errx(1, "pread succeeded on tty, returning %d", ret);
75 	else if (errno != ESPIPE)
76 		err(1, "pread");
77 
78 	return 0;
79 }
80