#include <unistd.h> int getgroups(int size, gid_t list[_Nullable size]); #include <grp.h> int setgroups(size_t size, const gid_t list[size]);
glibc 向けの機能検査マクロの要件 (feature_test_macros(7) 参照):
setgroups():
Since glibc 2.19:
_DEFAULT_SOURCE
glibc 2.19 and earlier:
_BSD_SOURCE
この関数を呼び出したプロセスの実効グループ ID が、 返されるリストに含まれるかどうかは規定されていない (したがって、アプリケーションは getegid(2) を呼び出し、その結果の値を追加・削除すべきである)。
size が 0 ならば、 list は修正されないが、そのプロセスの補助グループ ID の合計数が返される。 これを使うことで、それ以降の getgroups() の呼び出しで必要となる動的割り当てバッファー list のサイズを、呼び出し元が決定することができる。
setgroups() sets the supplementary group IDs for the calling process. Appropriate privileges are required (see the description of the EPERM error, below). The size argument specifies the number of supplementary group IDs in the buffer pointed to by list. A process can drop all of its supplementary groups with the call:
setgroups(0, (gid_t [0]){});
On success, setgroups() returns 0. On error, -1 is returned, and errno is set to indicate the error.
getgroups() は、上記に加えて以下のエラーで失敗する可能性がある。
setgroups() は、上記に加えて以下のエラーで失敗する可能性がある。
元々の Linux の getgroups() システムコールは 16 ビットのグループ ID だけ に対応していた。その後、Linux 2.4 で、32 ビットの ID に対応した getgroups() が追加された。glibc の getgroups のラッパー関数はカーネル バージョンによるこの違いを吸収している。
補助グループ ID の最大数は、実行時に sysconf(3) を使って以下のようにして調べることができる:
long ngroups_max; ngroups_max = sysconf(_SC_NGROUPS_MAX);
getgroups() の返り値の最大値は、この値より大きくなることはない。 Linux 2.6.4 以降では、補助グループ ID の最大数も Linux 固有の読み込み専用のファイル /proc/sys/kernel/ngroups_max 経由で公開されている。
#include <err.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#define MALLOC(n, T) ((T *) reallocarray(NULL, n, sizeof(T)))
static gid_t *agetgroups(size_t *ngids);
int
main(void)
{
gid_t *gids;
size_t n;
gids = agetgroups(&n);
if (gids == NULL)
err(EXIT_FAILURE, "agetgroups");
if (n != 0) {
printf("%jd", (intmax_t) gids[0]);
for (size_t i = 1; i < n; i++)
printf(" %jd", (intmax_t) gids[i]);
}
puts("");
free(gids);
exit(EXIT_SUCCESS);
}
static gid_t *
agetgroups(size_t *ngids)
{
int n;
gid_t *gids;
n = getgroups(0, NULL);
if (n == -1)
return NULL;
gids = MALLOC(n, gid_t);
if (gids == NULL)
return NULL;
n = getgroups(n, gids);
if (n == -1) {
free(gids);
return NULL;
}
*ngids = n;
return gids;
}