xref: /titanic_52/usr/src/ucbcmd/users/users.c (revision 1a7c1b724419d3cb5fa6eea75123c6b2060ba31b)
1 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
2 /*	  All Rights Reserved  	*/
3 
4 
5 /*
6  * Copyright (c) 1980 Regents of the University of California.
7  * All rights reserved.  The Berkeley software License Agreement
8  * specifies the terms and conditions for redistribution.
9  */
10 
11 /*
12  * Copyright (c) 1983-1998 by Sun Microsystems, Inc.
13  * All rights reserved.
14  */
15 
16 #ident	"%Z%%M%	%I%	%E% SMI"	/* SVr4.0 1.1	*/
17 
18 /*
19  * users
20  */
21 
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <stdlib.h>
25 #include <utmpx.h>
26 
27 static	char	*strndup(char *p, int n);
28 
29 struct utmpx *utmpx;
30 char	**names;
31 char	**namp;
32 
33 main(argc, argv)
34 char **argv;
35 {
36 	char	 *tp;
37 	int	nusers = 0;
38 	int	bufflen = BUFSIZ;
39 
40 	if (argc == 2)
41 		if (!utmpxname(argv[1])) {
42 			fprintf(stderr, "Filename is too long\n");
43 			exit(1);
44 		}
45 
46 	names = namp = (char **)realloc((void *)NULL, BUFSIZ * sizeof (char *));
47 
48 	setutxent();
49 
50 	while ((utmpx = getutxent()) != NULL) {
51 		if (utmpx->ut_name[0] == '\0')
52 			continue;
53 		if (utmpx->ut_type != USER_PROCESS)
54 			continue;
55 		if (nonuserx(*utmpx))
56 			continue;
57 		if (nusers == bufflen) {
58 			bufflen *= 2;
59 			names = (char **)realloc(names,
60 						bufflen * sizeof (char *));
61 			namp = names + nusers;
62 		}
63 		*namp++ = strndup(utmpx->ut_name, sizeof (utmpx->ut_name));
64 		nusers++;
65 	}
66 
67 	endutxent();
68 
69 	summary();
70 	exit(0);
71 }
72 
73 static	char	*
74 strndup(char *p, int n)
75 {
76 
77 	register char	*x;
78 	x = malloc(n + 1);
79 	strncpy(x, p, n);
80 	*(x + n) = '\0';
81 	return (x);
82 
83 }
84 
85 scmp(const void *p, const void *q)
86 {
87 	return (strcmp((char *)p, (char *)q));
88 }
89 
90 summary()
91 {
92 	register char **p;
93 
94 	qsort(names, namp - names, sizeof (names[0]), scmp);
95 	for (p = names; p < namp; p++) {
96 		if (p != names)
97 			putchar(' ');
98 		fputs(*p, stdout);
99 	}
100 	if (namp != names)		/* at least one user */
101 		putchar('\n');
102 }
103