fluffy
fluffy

Reputation: 5314

Getting the current user account's display name in UNIX-type operating systems

In Windows, the user account has both an account name and a "real name" associated with the account. This can be retrieved by GetUserNameEx().

Similarly, in UNIX-type operating systems, there's the "finger info" (as set by chfn and the like, as well as through various GUI tools on desktop UNIXen). How can this information be retrieved by a user process in UNIX-type OSes (such as macOS and Linux)?

An ideal solution would use the libc API, without relying on just spawning a finger process or the like.

Upvotes: 0

Views: 850

Answers (2)

fluffy
fluffy

Reputation: 5314

Shell-scripting solution:

On Linux, you can use getent passwd in a subprocess, and then parse out the realname field (which should be the fifth one between commas).

On macOS, you can use id -f.

Upvotes: 0

sjnarv
sjnarv

Reputation: 2384

I'd probably call getuid, then getpwuid or getpwuid_r, on Unix-like systems.

Something like:

#include <pwd.h>
#include <stdio.h>
#include <unistd.h>

int
main(void)
{
    struct passwd *pw;

    pw = getpwuid(getuid());

    if (pw == 0) {
        perror("getpwuid failed");
        return 1;
    }

    printf("username: %s; realname: '%s'\n", pw->pw_name, pw->pw_gecos);

    return 0;
}

Upvotes: 1

Related Questions