-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathgetgrgid.cpp
More file actions
68 lines (57 loc) · 1.27 KB
/
Copy pathgetgrgid.cpp
File metadata and controls
68 lines (57 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! @brief returns the groupname for a gid
#include "getgrgid.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <grp.h>
#include <string.h>
#include <unistd.h>
//! @brief GetGrGid returns the groupname for a gid
//!
//! GetGrGid
//!
//! @param[in] gid
//! @parblock
//! The group identifier to lookup.
//! @endparblock
//!
//! @retval groupname as UTF-8 string, or NULL if unsuccessful
//!
char* GetGrGid(gid_t gid)
{
int32_t ret = 0;
struct group grp;
struct group* result = NULL;
char* buf;
int buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
if (buflen < 1)
{
buflen = 2048;
}
allocate:
buf = (char*)calloc(buflen, sizeof(char));
errno = 0;
ret = getgrgid_r(gid, &grp, buf, buflen, &result);
if (ret != 0)
{
if (errno == ERANGE)
{
free(buf);
buflen *= 2;
goto allocate;
}
return NULL;
}
// no group found
if (result == NULL)
{
return NULL;
}
// allocate copy on heap so CLR can free it
size_t userlen = strnlen(grp.gr_name, buflen);
char* groupname = strndup(grp.gr_name, userlen);
free(buf);
return groupname;
}