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