Proper way to get groups of a user in linux using C

北城余情 提交于 2019-12-01 17:49:11
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);

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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!