summaryrefslogtreecommitdiff
path: root/usr/src/ucbcmd/users/users.c
blob: 707bcff8ba8f592d68c88ea6ed3295b03f4b7506 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Copyright (c) 1990, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/

/*
 * Copyright (c) 1980 Regents of the University of California.
 * All rights reserved.  The Berkeley software License Agreement
 * specifies the terms and conditions for redistribution.
 */

/*
 * users
 */

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <utmpx.h>
#include <string.h>

static char **names;
static char **namp;

static int scmp(const void *p, const void *q);
static void summary(void);

int
main(int argc, char **argv)
{
	int	nusers = 0;
	int	bufflen = BUFSIZ;
	struct utmpx *utmpx;

	if (argc == 2)
		if (!utmpxname(argv[1])) {
			(void) fprintf(stderr, "Filename is too long\n");
			exit(1);
		}

	names = namp = (char **)realloc((void *)NULL, BUFSIZ * sizeof (char *));

	setutxent();

	while ((utmpx = getutxent()) != NULL) {
		if (utmpx->ut_name[0] == '\0')
			continue;
		if (utmpx->ut_type != USER_PROCESS)
			continue;
		if (nonuserx(*utmpx))
			continue;
		if (nusers == bufflen) {
			bufflen *= 2;
			names = (char **)realloc(names,
			    bufflen * sizeof (char *));
			namp = names + nusers;
		}
		*namp++ = strndup(utmpx->ut_name, sizeof (utmpx->ut_name));
		nusers++;
	}

	endutxent();

	summary();
	return (0);
}

static int
scmp(const void *p, const void *q)
{
	return (strcmp((char *)p, (char *)q));
}

static void
summary(void)
{
	register char **p;

	qsort(names, namp - names, sizeof (names[0]), scmp);
	for (p = names; p < namp; p++) {
		if (p != names)
			(void) putchar(' ');
		(void) fputs(*p, stdout);
	}
	if (namp != names)		/* at least one user */
		(void) putchar('\n');
}