getlogin_r - Linux


getlogin_r retrieves the username of the user running the current process. It is commonly used in multithreaded applications where the username may change dynamically, and it is crucial to obtain the correct username in a thread-safe manner.


int getlogin_r(char *name, size_t namelen);


  • name: Pointer to a buffer that will store the retrieved username.
  • namelen: The size of the buffer pointed to by name.

Return Value

getlogin_r returns:

  • 0 on success, meaning the username was successfully retrieved and stored in the buffer.
  • A non-zero value to indicate an error, such as:
    • ERANGE: Buffer too small to hold the username.


Simple Example:

Retrieve and print the username:

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

int main() {
    char username[50]; // Assuming a reasonable buffer size
    if (getlogin_r(username, sizeof(username)) == 0) {
        printf("Current user: %s\n", username);
    } else {
        printf("Error getting username\n");
    return 0;

Multithreaded Example:

Retrieve the username within a thread-safe function:

#include <pthread.h>
#include <string.h>

// Function to be executed as a thread
void *get_username(void *data) {
    char username[50];
    if (getlogin_r(username, sizeof(username)) == 0) {
        // Use the username within the thread
    } else {
        // Handle the error
    return NULL;

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, get_username, NULL);
    pthread_join(tid, NULL);
    return 0;

Common Issues

  • Insufficient buffer size: Ensure the namelen parameter is sufficient to hold the username, otherwise you may encounter ERANGE error.
  • Concurrent username changes: If the username changes while getlogin_r is executing, it may not retrieve the most up-to-date username.


getlogin_r can be integrated with:

  • setlogin(2): To set the username in a multithreaded environment.
  • getpwnam(3): To retrieve user information based on the username.
  • PAM (Pluggable Authentication Modules): To obtain the username in a security-aware manner.

Related Commands

  • getlogin: Non-reentrant version of getlogin_r.
  • whoami: Prints the effective username and group.
  • env(1): Prints environment variables, including the username.