Chapter Contents

Previous

Next
getgroupsbyname

getgroupsbyname



Determine Supplementary Group IDs for a User Name

Portability: SAS/C extension


SYNOPSIS
DESCRIPTION
RETURN VALUE
PORTABILITY
EXAMPLE
RELATED FUNCTIONS


SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int getgroupsbyname(char * userID, int listSize, gid_t groupList[ ]  );


DESCRIPTION

getgroupsbyname stores the supplementary group IDs for a specified user into an array.

userID
identifies the user.

listSize
is the number of elements that can be stored in the array.

groupList
is a pointer to the array used to store the supplementary user IDs.


RETURN VALUE

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.


PORTABILITY

The getgroupsbyname function is not defined by the POSIX.1 standard and should not be used in portable applications.


EXAMPLE

The following example illustrates the use of getgroupsbyname to determine the groups that a user belongs to.

Note:    You must specify the posix option when compiling this example.  [cautionend]

#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 %s\n",
                      argv[2], argv[1]);
   else printf("Group %s was not found for user %s\n",
                argv[2], argv[1]);
}


RELATED FUNCTIONS

getgroups


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.