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.
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.
#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;
}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.