GETGROUPLIST - Linux手册页

Linux程序员手册 第3部分
更新日期: 2020-06-09

示例

下面的程序显示在第一个命令行参数中命名的用户的组列表。第二个命令行参数指定要提供给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 j, ngroups;
    gid_t *groups;
    struct passwd *pw;
    struct group *gr;

    if (argc != 3) {
        fprintf(stderr, "Usage: %s <user> <ngroups>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    ngroups = atoi(argv[2]);

    groups = malloc(ngroups * sizeof (gid_t));
    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\n",
                ngroups);
        exit(EXIT_FAILURE);
    }

    /* Display list of retrieved groups, along with group names */

    fprintf(stderr, "ngroups = %d\n", ngroups);
    for (j = 0; j < ngroups; j++) {
        printf("%d", groups[j]);
        gr = getgrgid(groups[j]);
        if (gr != NULL)
            printf(" (%s)", gr->gr_name);
        printf("\n");
    }

    exit(EXIT_SUCCESS);
}

属性

有关本节中使用的术语的说明,请参见attribute(7)。

InterfaceAttributeValue
getgrouplist()Thread safetyMT-Safe locale

另外参见

getgroups(2),setgroups(2),getgrent(3),group_member(3),group(5),passwd(5)

说明

getgrouplist()函数扫描组数据库(请参阅group(5))以获得用户所属的组的列表。数组组中最多返回* ngroup个这些组。

如果它不在组数据库中为用户定义的组中,则该组将包含在由getgrouplist()返回的组列表中;通常,此参数从用户的密码记录中指定为组ID。

ngroups参数是一个值结果参数:返回时,它总是包含为用户找到的组数,包括组;此值可能大于存储在组中的组数。

出版信息

这个页面是Linux手册页项目5.08版的一部分。有关项目的说明、有关报告错误的信息以及此页面的最新版本,请访问https://www.kernel.org/doc/man-pages/

版本

自glibc 2.2.4起提供此功能。

遵循规范

此功能是非标准的;它出现在大多数BSD上。

BUGS

在2.3.3之前的glibc版本中,此函数的实现包含一个缓冲区溢出错误:即使组数超过* ngroups,它也会为阵列组中的用户返回组的完整列表。

名称

getgrouplist-获取用户所属的组的列表

语法

#包括

int getgrouplist(const char * user,gid_t group
gid_t * groups,int * ngroups);

glibc的功能测试宏要求(请参阅feature_test_macros(7)):

getgrouplist():
从glibc 2.19开始:
_DEFAULT_SOURCE
Glibc 2.19及更早版本:
_BSD_SOURCE

返回值

如果用户是其成员的组的数目小于或等于* ngroups,则返回值* ngroups。

如果用户是多个* ngroups组的成员,则getgrouplist()返回-1。在这种情况下,* ngroups中返回的值可用于调整传递给进一步调用getgrouplist()的缓冲区的大小。

日期:2019-08-20 18:00:28 来源:oir作者:oir