Decoded: logname (coreutils)

[Back to Project Main Page]

Note: This page explores the design of command-line utilities. It is not a user guide.
[GNU Manual] [POSIX requirement] [Linux man] [FreeBSD man]

Logical flow of logname command (coreutils)

Summary

logname - print current user's login name

[Source] [Code Walkthrough]

Lines of code: 90
Principal syscall: None
Support syscalls: None -- (getlogin() is not a syscall)
Options: 2 (help and version)

Spiritually linked to the System III UNIX LOGNAME environment variable (1982)
Added to Coreutils in November 1992 [First version]
Number of revisions: 92 [Code Evolution]

Helpers:
  • None
External non-standard helpers:
  • die() - Exit with mandatory non-zero error and message to stderr
  • error() - Outputs error message to standard error with possible process termination

Setup

logname only uses the default parsing options, which require no initialization

main() initializes one local variable, *cp, to hold the string pointer for the login name


Parsing

Parsing for logname involves two checks:

  • Check for any long options
  • Check for anything else

Parsing failures

Thess failure cases are explicitly checked:

  • If any non-long option is passed
  • If any argument is passed

This failure result in a short error message followed by the usage instructions.


Execution

Successful execution prints the result of a call to getlogin(). This function is system-dependent and is declared in specific headers (ex: unistd.h).

For example, on the system I'm using to type this, getlogin pushes /proc/self/loginuid through getpwuid()

Execution could fail if getlogin() doesn't return a valid pointer

Extra comments

logname vs whoami

Both commands return user names that often match...but not always. Consider this:

$ whoami
maizure
$ logname
maizure


$ sudo whoami
root
$ sudo logname
maizure

whoami returns the effective user id running the process using geteuid(). sudo temporarily changes the effective user.

logname returns the user name of whoever launched the terminal -- typically the user logged in to the system. My system pulls this info from /proc/self/loginuid

Fun fact: Comparing results between geteuid() and /proc/self/loginuid is a common check for altered execution state in your scripts and utilities


[Back to Project Main Page]