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 /** 19 * give the name of a tty fd. threadsafe. 20 * @param fd the tty to get the name from. 21 * @param buffer where to store the name to. 22 * @param bufferSize length of the buffer. 23 * @return 0 on success, -1 on error, sets errno. 24 */ 25 int 26 ttyname_r(int fd, char *buffer, size_t bufferSize) 27 { 28 struct stat fdStat; 29 30 // first, some sanity checks: 31 if (fstat(fd, &fdStat) < 0) 32 return -1; 33 34 if (!S_ISCHR(fdStat.st_mode) || !isatty(fd)) { 35 errno = ENOTTY; 36 return ENOTTY; 37 } 38 39 // just ask devfs 40 return ioctl(fd, B_GET_PATH_FOR_DEVICE, buffer, bufferSize); 41 } 42 43 44 /** 45 * give the name of a tty fd. 46 * @param fd the tty to get the name from. 47 * @return the name of the tty or NULL on error. 48 */ 49 char * 50 ttyname(int fd) 51 { 52 static char pathname[MAXPATHLEN]; 53 54 int err = ttyname_r(fd, pathname, sizeof(pathname)); 55 if (err < 0) 56 return NULL; 57 return pathname; 58 } 59