1 /* 2 * Copyright 2003, Daniel Reinhold, danielre@users.sf.net. All rights reserved. 3 * Copyright 2007, François Revol, mmu_man@users.sf.net. All rights reserved. 4 * Distributed under the terms of the MIT License. 5 */ 6 7 8 #include <SupportDefs.h> 9 #include <Drivers.h> 10 11 #include <errno.h> 12 #include <stdio.h> 13 #include <string.h> 14 #include <unistd.h> 15 #include <sys/stat.h> 16 #include <sys/param.h> 17 18 #include <errno_private.h> 19 20 21 /** 22 * give the name of a tty fd. threadsafe. 23 * @param fd the tty to get the name from. 24 * @param buffer where to store the name to. 25 * @param bufferSize length of the buffer. 26 * @return 0 on success, -1 on error, sets errno. 27 */ 28 int 29 ttyname_r(int fd, char *buffer, size_t bufferSize) 30 { 31 struct stat fdStat; 32 33 // first, some sanity checks: 34 if (fstat(fd, &fdStat) < 0) 35 return ENOTTY; 36 37 if (!S_ISCHR(fdStat.st_mode) || !isatty(fd)) 38 return ENOTTY; 39 40 // just ask devfs 41 if (ioctl(fd, B_GET_PATH_FOR_DEVICE, buffer, bufferSize) < 0) 42 return errno; 43 return 0; 44 } 45 46 47 /** 48 * give the name of a tty fd. 49 * @param fd the tty to get the name from. 50 * @return the name of the tty or NULL on error. 51 */ 52 char * 53 ttyname(int fd) 54 { 55 static char pathname[MAXPATHLEN]; 56 57 int err = ttyname_r(fd, pathname, sizeof(pathname)); 58 if (err != 0) { 59 __set_errno(err); 60 return NULL; 61 } 62 return pathname; 63 } 64