我想知道unix命令组是否有任何备用C库,
$ groups ---- lists all the group id's of the user.
有一个名为getgroups()的方法,但它返回用户此方法的组。有没有办法使用C为特定用户获取组。
答案 0 :(得分:4)
#include "<grp.h>"
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
答案 1 :(得分:1)
这里是一个如何使用getgrouplist进行操作的示例,您可以随时提出任何问题。
__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);
}