我是新来的MAC,目前正在做一些项目,这里是代码:
#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <errno.h> #include <grp.h> #include <pwd.h> #include <string.h> int GetSuplementaryGroups(const char *userName, gid_t *&groups, int &groupc) { gid_t *suplementaryGroups = NULL; int ngroups = 0; int result = -1; struct passwd *pw; pw = getpwnam(userName); if (pw == NULL) { fprintf(stderr, "Error is %d.\n", errno); return -1; } #ifdef __APPLE__ ngroups = 100; #else result = getgrouplist(userName, pw -> pw_gid, suplementaryGroups, &ngroups); #endif suplementaryGroups = new gid_t [ngroups]; #ifdef __APPLE__ while (true) { int oldNgroups = ngroups; result = getgrouplist(userName, pw -> pw_gid, (int *) suplementaryGroups, &ngroups); if (result == -1 && ngroups == oldNgroups) { delete [] suplementaryGroups; ngroups += 100; suplementaryGroups = new gid_t [ngroups]; } else { break; } } #else result = getgrouplist(userName, pw -> pw_gid, suplementaryGroups, &ngroups); #endif printf("Result: '%d', number of groups %d.\n", result, ngroups); groups = suplementaryGroups; groupc = ngroups; return result; } int main() { int ngroups = 0; gid_t *sgroups = NULL; char userc[1024] = {0}; strncpy(userc, "root", 1024); if(GetSuplementaryGroups(userc, sgroups, ngroups) == -1) { fprintf(stderr, "Error is %d\n", errno); } if (setgroups(ngroups, sgroups) == -1) { fprintf(stderr, "Error is %d\n", errno); } }
我无法粘贴整个代码,所以我硬编码了一些值。
我在这里尝试的是扫描用户所属的所有组的组数据库(在本例中为root
),并为调用进程设置补充组ID。 它适用于Linux给结果:
Result: '1', number of groups 1.
但在MAC(10.12.05)上输出失败:
Result: '0', number of groups 23. error is 22
作为setgroups
主页面,当size is greater than NGROUPS_MAX (32 before Linux 2.6.4; 65536 since Linux 2.6.4).
时返回EINVAL
size is greater than NGROUPS_MAX (32 before Linux 2.6.4; 65536 since Linux 2.6.4).
但它的23
,应该不应该是这个问题。
我想这个问题是getgrouplist
函数返回0
(和主页面说, he return value from the function is the number of group IDs actually stored
)。 但我不明白为什么会发生这种情况。
PS我手动更改了setgroups
函数的ngroups
参数为10
,在这种情况下,一切工作正常,我现在更困惑:)