Skip to content
systemcoding.dev
Systems Programming

Get the current user name with getpwuid and geteuid

Look up the account name of the effective user in C with geteuid and getpwuid_r on Linux with glibc 2.41, without trusting the USER variable or getlogin.

2 min read
Summarize in AI

getenv("USER") is whatever the parent put there, and getlogin() reads the terminal's login record, which is empty in a daemon, a container or a cron job. The reliable source is the account database, keyed by the effective user id: geteuid for the id and [getpwuid_r](https://man7.org/linux/man-pages/man3/getpwnam.3.html) for the record.

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

int main(void) {
    struct passwd pw, *result;
    char buf[1024];

    int err = getpwuid_r(geteuid(), &pw, buf, sizeof buf, &result);
    if (err != 0 || result == NULL) {
        fprintf(stderr, "no passwd entry for uid %u\n", (unsigned)geteuid());
        return 1;
    }
    printf("%s (uid %u)\n", pw.pw_name, (unsigned)pw.pw_uid);
    return 0;
}
Text
alice (uid 1000)

The _r variant writes into your buffer, so it is safe from several threads, unlike plain getpwuid, which returns a pointer to static storage that the next lookup overwrites. If the buffer is too small, the call returns ERANGE and you retry with a bigger one; sysconf(_SC_GETPW_R_SIZE_MAX) gives a starting size.

Two outcomes need handling. A uid with no entry, common in containers started with --user 1234, gives result == NULL and err == 0, so check both. And geteuid is the right id for "who am I acting as", while getuid is the one that started the process: they differ in a setuid program, and the name of the effective user is root there.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.