Use getresuid (2) or some of the more specific id lookup functions to get the desired identifier (real, effective, or saved) set) (you probably want a RUID if you want to emulate getlogin , in which case you can just call getuid and forget about the efficient and saved uid), and then use getpwuid (3) or its repeated instance to translate this value into the user identifier string.
getenv("USER") can give you the same result, but you cannot rely on it if you want real security.
Technically, all of them may differ from the result obtained by getlogin when stdin is your control terminal. If you really need the same answer as getlogin for you, you can temporarily direct your fd 0 to your control terminal, then call getlogin and then restore your fd 0:
int saved_fd0; if(0>(saved_fd0 = dup(0)) ; close(0); if(0>open("/dev/tty", O_RDONLY)) ; if(0>dup2(saved_fd0, 0)) ;
source share