getgrouplist函数用法详解
getgrouplist函数简介
- 头文件包含
#include <grp.h>
- 函数定义
int getgrouplist(const char * user , gid_t group ,
gid_t * groups , int * ngroups );
getgrouplist函数常见使用错误
- 编译错误
warning: implicit declaration of function ‘getgrouplist’ [-Wimplicit-function-declaration]
解决办法:包含头文件
#include <grp.h>
getgrouplist函数详细描述
getgrouplist ()函数扫描组数据库(请参阅group (5))以获得user所属组的列表。在数组groups 中最多返回这些组中的*ngroups
如果group不在组数据库中为user定义的组中,则PPPP1包含在getgrouplist ();返回的组列表中。通常,此参数被指定为user 密码记录中的组ID
ngroups参数是一个值-结果参数:返回时,它总是包含为user 找到的组数,包括group ;。该值可能大于groups 中存储的组数
getgrouplist函数返回值
如果user所属的组数小于或等于ngroups ,则返回值ngroups。
如果用户是多个ngroups组的成员,则getgrouplist ()返回-1。在这种情况下,可以使用ngroups中返回的值来调整传递给另一个调用getgrouplist ()的缓冲区的大小
getgrouplist函数使用举例
下面的程序显示在其第一个命令行参数中命名的用户的组列表。第二个命令行参数指定要提供给getgrouplist ()的ngroups值。下面的shell会话显示了此程序的使用示例:
" ./a.out cecilia 0"
getgrouplist() returned \-1; ngroups = 3
" ./a.out cecilia 3"
ngroups = 3
16 (dialout)
33 (video)
100 (users)
Program source&
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>
#include <pwd.h>
int
main(int argc, char *argv[])
{
int ngroups;
struct passwd *pw;
struct group *gr;
if (argc != 3) {
fprintf(stderr, "Usage: %s <user> <ngroups>\en", argv[0]);
exit(EXIT_FAILURE);
}
ngroups = atoi(argv[2]);
gid_t *groups = malloc(sizeof(*groups) * ngroups);
if (groups == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
/* Fetch passwd structure (contains first group ID for user) */
pw = getpwnam(argv[1]);
if (pw == NULL) {
perror("getpwnam");
exit(EXIT_SUCCESS);
}
/* Retrieve group list */
if (getgrouplist(argv[1], pw\->pw_gid, groups, &ngroups) == \-1) {
fprintf(stderr, "getgrouplist() returned \-1; ngroups = %d\en",
ngroups);
exit(EXIT_FAILURE);
}
/* Display list of retrieved groups, along with group names */
fprintf(stderr, "ngroups = %d\en", ngroups);
for (int j = 0; j < ngroups; j++) {
printf("%d", groups[j]);
gr = getgrgid(groups[j]);
if (gr != NULL)
printf(" (%s)", gr\->gr_name);
printf("\en");
}
exit(EXIT_SUCCESS);
}
评论区