#include <sys/types.h> #include <unistd.h> int getgroupsbyname(char * userID, int listSize, gid_t groupList[]);
getgroupsbyname
stores the supplementary group IDs for a
specified user into an array.
userID
listSize
groupList
getgroupsbyname
returns 1
plus the number of supplementary group IDs
in groupList
. This value is always less than or equal to the
value
of NGROUPS_MAX
defined
in <limits.h>
. If listSize
is 0
,
getgroups
returns the total number of supplementary group IDs
and does not store the group IDs in an array. getgroups
returns a -1
if unsuccessful.
getgroupsbyname
function
is not defined by the POSIX.1 standard and should not be used
in portable applications.
getgroupsbyname
to determine the groups that a user belongs to.
Note:
You must specify the posix
option when compiling this example.
#include <sys/types.h> #include <unistd.h> #include <grp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> main(int argc, char *argv[]) { gid_t *groupIDs; int maxGroups; int argGroupID; struct group *argGroup; int i; int found; if (argc < 3) { fprintf(stderr, "Two arguments required: username groupnamen"); abort(); } maxGroups = getgroupsbyname(argv[1], 0, NULL); /* determine number of supplemental groups */ if (maxGroups <= 0) { perror("getgroupsbyname error"); abort(); } groupIDs = malloc(maxGroups * sizeof(gid_t)); if (!groupIDs) abort(); maxGroups = getgroupsbyname(argv[1], maxGroups, groupIDs); if (maxGroups <= 0) { perror("getgroupsbyname error"); abort(); } argGroup = getgrnam(argv[2]); /* look up group name */ if (!argGroup) { perror("getgrnam error"); abort(); } argGroupID = argGroup->gr_gid; found = 0; for (i = 0; i < maxGroups; ++i) { if (groupIDs[i] == argGroupID) { found = 1; break; } } if (found) printf("Group %s was found for user %sn", argv[2], argv[1]); else printf("Group %s was not found for user %sn", argv[2], argv[1]); }
getgroups