getlogin() — Get the user login name

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

_POSIX_SOURCE:
#define _POSIX_SOURCE
#include <unistd.h>

char *getlogin(void);
_XOPEN_SOURCE:
#define _XOPEN_SOURCE
#include <unistd.h>

char *getlogin(void);

General description

Finds the name that the login process associated with the current terminal. This string is stored in a static data area and, therefore, may be overwritten with every call to getlogin().

Special behavior for _POSIX_SOURCE: If called from a batch program, a TSO command, or a shell command, getlogin() returns the MVS™ user name associated with the program. With z/OS® UNIX services, this name is a TSO/E user ID. When _POSIX_SOURCE is defined and _XOPEN_SOURCE is not defined, then getlogin() is the same as __getlogin1().

Special behavior for XPG4.2: You must have a TTY at file descriptor 0, 1, or 2, and the TTY must be recorded in the /etc/utmpx database. Someone must have logged in using the TTY. Also, the program must be invoked from a shell session, and file descriptors 0, 1, and 2 are not all redirected.

If getlogin() cannot determine the login name, you can call getuid() to get the user ID of the process, and then call getpwuid() to get a login name associated with that user ID. getpwuid() always returns the passwd struct for the same user, even if multiple users have the same UID.

Returned value

If successful, getlogin() returns a pointer to a string that has the login name for the current terminal.

Special behavior for _POSIX_SOURCE: If unsuccessful, getlogin() returns the NULL pointer.

There are no documented errno values.

Special behavior for XPG4.2: If unsuccessful, getlogin() returns a NULL pointer and sets errno to one of the following values:
Error Code
Description
EMFILE
OPEN_MAX file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.
ENXIO
The calling process has no controlling terminal.

Example

CELEBG12
⁄* CELEBG12

   This example gets the user login name.

 *⁄
#define _POSIX_SOURCE
#include <stdio.h>
#include <unistd.h>

main() {
  char *user;

  if ((user = __getlogin1()) == NULL)
    perror("__getlogin1() error");
  else printf("__getlogin1() returned %s\n", user);
}
Output
getlogin() returned MEGA

Related information