fluffy fluffy - 2 months ago 13
Linux Question

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

.

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.

Answer

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;
}
Comments