xref: /csrg-svn/lib/libc/gen/ttyslot.c (revision 16277)
1*16277Ssam /* @(#)ttyslot.c	4.2 (Berkeley) 04/03/84 */
2*16277Ssam 
31995Swnj /*
41995Swnj  * Return the number of the slot in the utmp file
51995Swnj  * corresponding to the current user: try for file 0, 1, 2.
61995Swnj  * Definition is the line number in the /etc/ttys file.
71995Swnj  */
8*16277Ssam #include <sys/file.h>
91995Swnj 
101995Swnj char	*ttyname();
111995Swnj char	*getttys();
121995Swnj char	*rindex();
131995Swnj static	char	ttys[]	= "/etc/ttys";
141995Swnj 
151995Swnj #define	NULL	0
161995Swnj 
171995Swnj ttyslot()
181995Swnj {
191995Swnj 	register char *tp, *p;
201995Swnj 	register s, tf;
211995Swnj 
22*16277Ssam 	if ((tp = ttyname(0)) == NULL &&
23*16277Ssam 	    (tp = ttyname(1)) == NULL &&
24*16277Ssam 	    (tp = ttyname(2)) == NULL)
251995Swnj 		return(0);
261995Swnj 	if ((p = rindex(tp, '/')) == NULL)
271995Swnj 		p = tp;
281995Swnj 	else
291995Swnj 		p++;
30*16277Ssam 	if ((tf = open(ttys, O_RDONLY)) < 0)
31*16277Ssam 		return (0);
321995Swnj 	s = 0;
331995Swnj 	while (tp = getttys(tf)) {
341995Swnj 		s++;
35*16277Ssam 		if (strcmp(p, tp) == 0) {
361995Swnj 			close(tf);
37*16277Ssam 			return (s);
381995Swnj 		}
391995Swnj 	}
401995Swnj 	close(tf);
41*16277Ssam 	return (0);
421995Swnj }
431995Swnj 
44*16277Ssam #define	BUFSIZ	1024
45*16277Ssam 
461995Swnj static char *
471995Swnj getttys(f)
481995Swnj {
49*16277Ssam 	static char buf[BUFSIZ + 1], *next = &buf[BUFSIZ + 1];
501995Swnj 	register char *lp;
51*16277Ssam 	char *start;
521995Swnj 
531995Swnj 	for (;;) {
54*16277Ssam 		if (next >= &buf[BUFSIZ]) {
55*16277Ssam 			int n = read(f, buf, BUFSIZ);
56*16277Ssam 
57*16277Ssam 			if (n <= 0)
58*16277Ssam 				return (NULL);
59*16277Ssam 			buf[n] = '\0';
60*16277Ssam 			next = &buf[0];
611995Swnj 		}
62*16277Ssam 		for (lp = next; *lp && *lp != '\n'; lp++)
63*16277Ssam 			;
64*16277Ssam 		if (*lp == '\n') {
65*16277Ssam 			*lp++ = '\0';
66*16277Ssam 			start = next;
67*16277Ssam 			next = lp;
68*16277Ssam 			return (start + 2);
69*16277Ssam 		}
70*16277Ssam 		lseek(f, next - lp, L_INCR);
71*16277Ssam 		next = lp;
721995Swnj 	}
731995Swnj }
74