xref: /titanic_52/usr/src/lib/libbc/libc/gen/common/ttyslot.c (revision c2580b931007758eab8cb5ae8726ebe1588e259b)
1 /*
2  * Copyright 1991 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1984 Regents of the University of California.
8  * All rights reserved.  The Berkeley software License Agreement
9  * specifies the terms and conditions for redistribution.
10  */
11 
12 #pragma ident	"%Z%%M%	%I%	%E% SMI"
13 
14 /*
15  * Return the number of the slot in the utmp file
16  * corresponding to the current user: try for file 0, 1, 2.
17  * To mimic the behavior of getttyent, we loop through utmp
18  * and try to find an entry with a matching line number.
19  * If we don't find one we return the index of the end of
20  * the file, so that the record can be added to the end of
21  * the file.
22  */
23 #include "../../sys/common/compat.h"
24 #include <sys/syscall.h>
25 #include <sys/fcntl.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <strings.h>
29 
30 int
31 ttyslot(void)
32 {
33 	char *tp, *p;
34 	int s;
35 	int fd;
36 	struct utmpx utx;
37 
38 
39 	if ((tp = ttyname(0)) == NULL &&
40 	    (tp = ttyname(1)) == NULL &&
41 	    (tp = ttyname(2)) == NULL)
42 		return(0);
43 	if ((p = rindex(tp, '/')) == NULL)
44 		p = tp;
45 	else
46 		p++;
47 
48 	if ((fd = _syscall(SYS_open, "/etc/utmpx", O_RDONLY)) == -1) {
49 		perror("ttyslot: open of /etc/utmpx failed:");
50 		return(0);
51 	}
52 
53 	s = 0;
54 	while (_read(fd, &utx, sizeof(struct utmpx)) > 0) {
55 		s++;
56 		if (strncmp(utx.ut_line, p, sizeof(utx.ut_line)) == 0) {
57 			_syscall(SYS_close, fd);
58 			return(s);
59 		}
60 	}
61 	_syscall(SYS_close, fd);
62 	return (s);
63 }
64