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

為{幸葍}努か 提交于 2019-12-19 18:58:27

问题


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.


回答1:


#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);



回答2:


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);
}


来源:https://stackoverflow.com/questions/22104383/proper-way-to-get-groups-of-a-user-in-linux-using-c

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