getgrnam_r - Linux


Overview

getgrnam_r retrieves a group structure containing the group entry with the given group name. It is used for thread-safe access to group database information.

Syntax

int getgrnam_r(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result)

Options/Flags

None

Examples

Simple usage:

struct group *group;
char buffer[1024];
group = getgrnam_r("users", NULL, buffer, sizeof(buffer), NULL);

Complex usage (error handling):

char buffer[1024];
struct group group;
int ret = getgrnam_r("users", &group, buffer, sizeof(buffer), &result);
if (ret == 0) {
    printf("Group name: %s\n", result->gr_name);
} else if (ret == ENOENT) {
    printf("Group not found.\n");
} else {
    perror("getgrnam_r error");
}

Common Issues

  • Incorrect group name: Ensure that the provided group name is valid and exists in the system’s group database.
  • Insufficient buffer size: Increase the size of the buf argument if the returned structure is truncated.

Integration

With getpwnam_r:

char buf[1024];
struct group *group;
struct passwd *user;
if (getgrnam_r("users", group, buf, sizeof(buf), NULL) == 0 &&
    getpwnam_r(group->gr_name, user, buf, sizeof(buf), NULL) == 0) {
    printf("User name: %s\n", user->pw_name);
}

Related Commands