8

I want to know if there is any alternate C library for the unix command groups,

$ groups ---- lists all the group id's of the user.

There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.

ekad
  • 14,436
  • 26
  • 44
  • 46
Adi GuN
  • 1,244
  • 3
  • 16
  • 38
  • "getgrent, setgrent, endgrent - get group file entry" with "getpwent, setpwent, endpwent - get password file entry" – ysdx Feb 28 '14 at 19:43

2 Answers2

4
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
Asblarf
  • 483
  • 1
  • 4
  • 14
  • 6
    For completeness: http://man7.org/linux/man-pages/man3/getgrouplist.3.html Also mind the bug (See the man-pages for details) – alk Feb 28 '14 at 19:56
  • Sorry but could you tell me how I can get groupid in order to use getgrouplist method? All I have is the username – Adi GuN Feb 28 '14 at 20:14
  • 1
    @AdiGuN, The man page has a code example that tells you how you get that information. – Asblarf Feb 28 '14 at 20:18
  • 2
    Maybe try putting a useful example instead of an manpage excerpt. – aaa90210 Apr 18 '16 at 22:31
3

Here is a example of how to do it using getgrouplist, feel free to ask anything.

__uid_t uid = getuid();//you can change this to be the uid that you want

struct passwd* pw = getpwuid(uid);
if(pw == NULL){
    perror("getpwuid error: ");
}

int ngroups = 0;

//this call is just to get the correct ngroups
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
__gid_t groups[ngroups];

//here we actually get the groups
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);


//example to print the groups name
for (int i = 0; i < ngroups; i++){
    struct group* gr = getgrgid(groups[i]);
    if(gr == NULL){
        perror("getgrgid error: ");
    }
    printf("%s\n",gr->gr_name);
}
  • i dont see how this compiles? you cant dynamically allocate the groups array in that way? you would need a new there? – lufthansa747 Mar 11 '21 at 21:14
  • If I recall correctly I was having some issues with dynamic (heap) allocation, so I tried allocating it in the stack and worked correctly. – Federico Ciuffardi Mar 11 '21 at 23:06
  • ah I see. I guess my point really is that the code line `__gid_t groups[ngroups];` should throw an error regarding ngroups not being known at compile time. The code above is attempting to dynamically allocate on the stack which doesnt really make sense. – lufthansa747 Mar 14 '21 at 05:35
  • Maybe this only works on c++. I didn't think about that possibility. If you manage to get it working on c, maybe with [alloca](http://www.kernel.org/doc/man-pages/online/pages/man3/alloca.3.html), edit my answer or post another one. – Federico Ciuffardi Mar 14 '21 at 21:07