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