Project

General

Profile

Feature #7024 ยป group.c

Test program - Jason King, 2020-11-24 01:26 AM

 
1
#define __EXTENSIONS__
2
#include <stdio.h>
3
#include <stdlib.h>
4
#include <pwd.h>
5
#include <grp.h>
6
#include <err.h>
7
#include <unistd.h>
8

    
9
extern const char *__progname;
10

    
11
static int
12
doit(const char *user, gid_t agroup, int *ngids)
13
{
14
	gid_t *gids;
15
	int i, ret;
16

    
17
	if ((gids = calloc(*ngids, sizeof (gid_t))) == NULL)
18
		err(EXIT_FAILURE, "calloc");
19

    
20
	if ((ret = getgrouplist(user, agroup, gids, ngids)) < 0) {
21
		free(gids);
22
		return (ret);
23
	}
24

    
25
	printf("getgrouplist returned %d\n", ret);
26
	printf("%s:", user);
27
	for (i = 0; i < ret; i++) {
28
		struct group *gr = getgrgid(gids[i]);
29

    
30
		if (gr == NULL)
31
			err(EXIT_FAILURE, "failed to lookup gid %d\n", gids[i]);
32

    
33
		printf("%s%s(%d)", (i > 0) ? ", " : " ", gr->gr_name, gids[i]);
34
	}
35
	fputc('\n', stdout);
36

    
37
	free(gids);
38
	return (ret);
39
}
40

    
41
int
42
main(int argc, char **argv)
43
{
44
	struct passwd *pw;
45
	long ngroups_max;
46
	int ngids = -1;
47
	int ret;
48

    
49
	if (argc < 3) {
50
		fprintf(stderr, "Usage: %s user size\n", __progname);
51
		return (1);
52
	}
53

    
54
	ngroups_max = sysconf(_SC_NGROUPS_MAX);
55
	printf("ngroups_max = %ld\n", ngroups_max);
56

    
57
	pw = getpwnam(argv[1]);
58
	if (pw == NULL)
59
		err(EXIT_FAILURE, "error looking up %s", argv[1]);
60

    
61
	ngids = atoi(argv[2]);
62
	if (ngids < 1)
63
		err(EXIT_FAILURE, "invalid size: %s\n", argv[2]);
64

    
65
	ret = doit(argv[1], pw->pw_gid, &ngids);
66
	printf("getgrouplist returned %d (ngids = %d)\n", ret, ngids);
67
	if (ret > 0)
68
		return (0);
69

    
70

    
71
	ret = doit(argv[1], pw->pw_gid, &ngids);
72
	printf("getgrouplist returned %d (ngids = %d)\n", ret, ngids);
73
	return (0);
74
}
    (1-1/1)