xref: /original-bsd/lib/libc/gen/ttyname.c (revision 183db9ee)
1 /*
2  * Copyright (c) 1988 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #if defined(LIBC_SCCS) && !defined(lint)
19 static char sccsid[] = "@(#)ttyname.c	5.3 (Berkeley) 08/31/88";
20 #endif /* LIBC_SCCS and not lint */
21 
22 #include <sys/types.h>
23 #include <sys/dir.h>
24 #include <sys/stat.h>
25 #include <sgtty.h>
26 
27 #define	DEVDIR	"/dev/"
28 
29 char *
30 ttyname(fd)
31 	int fd;
32 {
33 	register struct direct *dirp;
34 	register DIR *dp;
35 	struct stat sb1, sb2;
36 	struct sgttyb ttyb;
37 	static char buf[sizeof(DEVDIR) + MAXNAMLEN] = DEVDIR;
38 	char *rval, *strcpy();
39 
40 	if (ioctl(fd, TIOCGETP, &ttyb) < 0)
41 		return(NULL);
42 	if (fstat(fd, &sb1) < 0 || (sb1.st_mode&S_IFMT) != S_IFCHR)
43 		return(NULL);
44 	if ((dp = opendir(DEVDIR)) == NULL)
45 		return(NULL);
46 	for (rval = NULL; dirp = readdir(dp);) {
47 		if (dirp->d_ino != sb1.st_ino)
48 			continue;
49 		(void)strcpy(buf + sizeof(DEVDIR) - 1, dirp->d_name);
50 		if (stat(buf, &sb2) < 0 || sb1.st_dev != sb2.st_dev ||
51 		    sb1.st_ino != sb1.st_ino)
52 			continue;
53 		closedir(dp);
54 		rval = buf;
55 		break;
56 	}
57 	closedir(dp);
58 	return(rval);
59 }
60