1 /* $OpenBSD: pwrite.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 <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 14 int 15 main(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 (pread(fd, buf, 10, 0) != 10) 48 err(1, "pread"); 49 50 if (memcmp(buf, "0000125400", 10) != 0) 51 errx(1, "data mismatch: %s != %s", buf, "0000125400"); 52 53 if ((ret = pwrite(fd, &magic[5], 1, -1)) != -1) 54 errx(1, "pwrite with negative offset succeeded,\ 55 returning %d", ret); 56 if (errno != EINVAL) 57 err(1, "pwrite with negative offset"); 58 59 if ((ret = pwrite(fd, &magic[5], 1, LLONG_MAX)) != -1) 60 errx(1, "pwrite with wrapping offset succeeded,\ 61 returning %d", ret); 62 if (errno != EFBIG && errno != EINVAL) 63 err(1, "pwrite with wrapping offset"); 64 65 /* pwrite should be unaffected by O_APPEND */ 66 if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_APPEND)) 67 err(1, "fcntl"); 68 if (pwrite(fd, &magic[2], 3, 2) != 3) 69 err(1, "pwrite"); 70 if (pread(fd, buf, 10, 0) != 10) 71 err(1, "pread"); 72 if (memcmp(buf, "0023425400", 10) != 0) 73 errx(1, "data mismatch: %s != %s", buf, "0023425400"); 74 75 close(fd); 76 77 /* also, verify that pwrite fails on ttys */ 78 fd = open("/dev/tty", O_RDWR); 79 if (fd < 0) 80 printf("skipping tty test\n"); 81 else if ((ret = pwrite(fd, &c, 1, 7)) != -1) 82 errx(1, "pwrite succeeded on tty, returning %d", ret); 83 else if (errno != ESPIPE) 84 err(1, "pwrite"); 85 86 return 0; 87 } 88