Decoded: tty (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 tty command (coreutils)

Summary

tty - print file name of terminal on standard input

[Source] [Code Walkthrough]

Lines of code: 134
Principal syscalls: None (ttyname() and isatty() are not syscalls)
Support syscall: None
Options: 5 (1 short, 4 long)

Descended from tty introduced in Version 2 UNIX (1972) //dmr&ken
Added to Shellutils in November 1992 [First version]
Number of revisions: 94 [Code Evolution]

Although they share names, the tty and stty utilities are unrelated

Helpers:
  • None
External non-standard helpers:
  • None

Setup

tty has two points to consider: Custom failure exit status and a global flag for silent mode

The failure exit status are as follows:

  • TTY_STDIN_NOTTY - No tty interface found
  • TTY_FAILURE - Usage failure
  • TTY_WRITE_ERROR - The defaut exit status reachable on uncaught failures (ie. bad puts() to the reported tty)

At global scope, we initialize a flag silent asserted if no output is to be provided (only exit status code). Initialized in main() as false by default.

main() defines optc to hold the current parsing option.


Parsing

The only task for parsing tty is if we need to enable silent mode.

Parsing failures

These failure cases are explicitly checked:

  • Using extra operands
  • An unknown option is used

Execution

The tty utility is simply a wrapper for the ttyname() or isatty() C library calls. The execution is as follows:

  • If silent mode, invokve isatty() as the return status
  • If not silent, get the tty file via ttyname()
  • If the name is value, print the name. Otherwise, print 'not a tty'

[Back to Project Main Page]