Linux 获取所有组的系统调用 - getgroups() 函数详解
Linux 系统中获取所有组的系统调用可以使用 'getgroups()' 函数。该函数的原型如下:
#include <unistd.h>
int getgroups(int size, gid_t list[]);
该函数的作用是获取当前进程所属的所有组。其中,'size' 参数指定 'list' 数组的长度,'list' 数组用于存储获取到的组 ID。如果 'list' 数组长度小于当前进程所属的组数,那么只会返回部分组 ID。如果 'list' 数组长度大于等于当前进程所属的组数,那么会返回所有组 ID,并且数组的前面部分为当前进程的主组 ID。
下面是一个示例程序,演示如何使用 'getgroups()' 函数获取所有组的系统调用:
#include <stdio.h>
#include <unistd.h>
#define MAX_GROUPS 16
int main()
{
gid_t groups[MAX_GROUPS];
int num_groups = getgroups(MAX_GROUPS, groups);
if (num_groups == -1) {
perror("getgroups");
return 1;
}
printf("The process belongs to %d groups:\n", num_groups);
for (int i = 0; i < num_groups; i++) {
printf("%d\n", groups[i]);
}
return 0;
}
在该程序中,我们首先定义了一个长度为 'MAX_GROUPS' 的数组 'groups',用于存储获取到的组 ID。然后调用 'getgroups()' 函数获取当前进程所属的所有组 ID,并将返回值保存到 'num_groups' 变量中。如果 'getgroups()' 函数调用失败,那么会输出错误信息并返回 1。否则,程序会输出当前进程所属的所有组 ID。
原文地址: https://www.cveoy.top/t/topic/kpHg 著作权归作者所有。请勿转载和采集!