1 /* $OpenBSD: util.c,v 1.1 2018/11/06 18:11:11 anton Exp $ */ 2 3 /* 4 * Copyright (c) 2018 Anton Lindqvist <anton@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include <sys/wait.h> 20 21 #include <err.h> 22 #include <errno.h> 23 #include <limits.h> 24 #include <paths.h> 25 #include <stdio.h> 26 #include <stdlib.h> 27 #include <string.h> 28 #include <unistd.h> 29 30 #include "util.h" 31 32 static const char *tmpdir(void); 33 34 int 35 make_file(off_t size) 36 { 37 char template[PATH_MAX]; 38 const char *dir; 39 int fd, n; 40 41 dir = tmpdir(); 42 n = snprintf(template, sizeof(template), "%sflock.XXXXXX", dir); 43 if (n == -1 || n >= (int)sizeof(template)) 44 errc(1, ENAMETOOLONG, "%s", __func__); 45 46 fd = mkstemp(template); 47 if (fd == -1) 48 err(1, "mkstemp"); 49 if (ftruncate(fd, size) == -1) 50 err(1, "ftruncate"); 51 if (unlink(template) == -1) 52 err(1, "unlink"); 53 54 return (fd); 55 } 56 57 int 58 safe_waitpid(pid_t pid) 59 { 60 int save_errno; 61 int status; 62 63 save_errno = errno; 64 errno = 0; 65 while (waitpid(pid, &status, 0) != pid) { 66 if (errno == EINTR) 67 continue; 68 err(1, "waitpid"); 69 } 70 errno = save_errno; 71 72 return (status); 73 } 74 75 __dead void 76 usage(void) 77 { 78 fprintf(stderr, "usage: %s [-v] testnum\n", getprogname()); 79 exit(1); 80 } 81 82 static const char * 83 tmpdir(void) 84 { 85 static char path[PATH_MAX]; 86 const char *p; 87 size_t len; 88 int n; 89 int nosuffix = 1; 90 91 p = getenv("TMPDIR"); 92 if (p == NULL || *p == '\0') 93 p = _PATH_TMP; 94 len = strlen(p); 95 if (len == 0) 96 errx(1, "%s: empty path", __func__); 97 if (p[len - 1] == '/') 98 nosuffix = 0; 99 n = snprintf(path, sizeof(path), "%s%s", p, nosuffix ? "/" : ""); 100 if (n == -1 || n >= (int)sizeof(path)) 101 errc(1, ENAMETOOLONG, "%s", __func__); 102 103 return (path); 104 } 105