The stty command in Linux provides low-level access to configure terminal settings, serial ports, input and output control, and more. Understanding stty is key for performance tuning and customizing your terminal environment.

In this comprehensive 2600+ word guide, you’ll master everything needed to become a stty power user including:

  • stty command syntax, options, and capabilities
  • Configuring baud rates for faster data transmission
  • Controlling terminal input and output processing
  • Modifying hardware signals and tty port settings
  • Usage examples for common terminal tasks
  • How stty is used by system internals and programs
  • Alternatives to stty and compatibility with other Unixes
  • Analyzing stty performance implications
  • Writing terminal games and interfaces with stty

So let’s dive in to truly master Linux’s stty terminal configuration tool!

What is the stty Command in Linux?

The stty command name stands for "set teletypewriter." It sets and manipulates various terminal communication parameters in Unix-like systems.

Some key capabilities of stty include:

  • Setting serial baud rates up to 921600 bps
  • Configuring number of data bits, parity, stop bits
  • Enabling/disabling hardware flow control signals
  • Controlling terminal driver input/output modes
  • Modifying tty port settings directly
  • Saving/restoring terminal configuration state

Internally, stty communicates with your system’s terminal driver to configure these low-level behavioral details. It ultimately makes ioctl system calls to modify driver state. This gives you finer-grained control than higher level shell tools.

Understanding stty gives Linux power users and sysadmins advanced control over terminal latency, throughput, error handling, job control, and display functionality.

Now let’s overview the command line options for using stty.

stty Command Line Syntax and Options

The basic syntax for using stty is:

stty [options] [<settings>]

Some commonly used command line options include:

  • -a – Print all current terminal settings in human-readable format
  • -g – Print all current settings in stty-readable format
  • -F device – Open and manipulate the specified device instead of stdin

For actually configuring settings, you pass in formatting like:

stty 115200 cs8 -cstopb -parenb -echo

Which would set 115200 baud rate, with 8n1 framing, no parity bit, one stop bit, and echo disabled.

Additional options like -h, –help, and -V, –version provide usage help and version info.

Next let’s look at applying stty for improved terminal performance…

Setting Terminal Baud Rates with stty

One common use of the stty command is to set terminal baud rates. The baud rate controls serial data transmission speeds.

With stty you can configure faster baud rates for reduced latency:

# Set baud rate to 115200 bps
stty 115200 

# Even faster rates like 500000+
stty 921600

Higher baud rates allow more data throughput per second over your terminal connection. This table shows common rates and throughput limits:

Baud Rate Max Throughput
9600 bps 960 bytes/sec
19200 bps 1920 bytes/sec
115200 bps 11.5 Kbytes/sec
921600 bps 90 Kbytes/sec

So when optimizing serial terminals or console device connections, test different stty bauds. Use the fastest stable rate your particular hardware supports for peak terminal performance.

Now let’s look at tuning input and output…

Configuring Terminal Input and Output Modes

stty also provides granular control over terminal input and output processing modes.

Some common settings to adjust I/O handling include:

  • icanon – Enable canonical (line-oriented) input mode
  • echo – Enable local input echoing
  • icrnl – Translate CR to NL on input
  • onlcr – Translate NL to CR+NL on output

For example to disable local echo and enable raw input:

stty -echo -icanon

Raw mode is useful for things like terminal user interfaces or games where you want direct keyboard scan codes.

To re-enable canonical input processing with echo:

stty echo icanon

Additional parameters like isig manage signal handling, while opost controls output processing.

There are over 50 different input and output modes to tweak advanced communication behavior. Consult the stty man pages for all available options.

Controlling Terminal Hardware Flow Signals

For direct serial device communication, stty offers control over RS-232 hardware flow signals.

Some interesting hardware flow settings include:

  • crtscts – Enable RTS/CTS handshaking flow control
  • ixoff – Enable start/stop input flow control
  • ixany – Allow any input to restart stopped output

For example to activate RTS/CTS hardware flow control:

stty -crtscts

This helps prevent serial receive overrun errors by regulating data rates between devices.

Other line signals like DTR/DSR can also be manipulated for testing or troubleshooting trickier serial communications issues.

Modifying TTY Port Settings Directly

In addition to configuring stdin/stdout behavior, stty can directly modify Linux tty device parameters:

# Set /dev/ttyS1 to 9600 baud 
stty -F /dev/ttyS1 9600

# Enable parity bit with even parity
stty -F /dev/ttyS1 cs8 parenb -parodd

This allows tweaking baud rate, parity, flow control, and other low-level port settings right from the shell.

So whether working with serial ports, console TTYs, pseudoterminals like /dev/pts/*, or even TCP/IP networks – stty gives you advanced control over their communication parameters.

Resetting stty Settings to Default State

To revert any changed settings back to system defaults:

stty sane

This will undo any modifications and restore normal terminal functionality system-wide.

You can also save stty settings to file, manipulate them, then reapply from file:

# Save current state
stty -g > mysettings

# Make changes..

# Restore saved config 
stty $(cat mysettings)

This provides an easy way to experiment with different stty tweaks without risking unusable terminals.

Next let’s walk through some common stty command use cases…

Helpful stty Command Examples

Here are handy examples for typical stty terminal configuration tasks:

Set High-Speed Baud Rate

stty 921600

Force Hardware Flow Control

stty -crtscts

Enter Raw Keyboard Input Mode

stty -icanon -echo

Set Serial Port Options

stty -F /dev/ttyS1 9600 cs8 parenb -cstopb

Print Entire stty Configuration

stty -a

Reset Terminal State to Default

stty sane

Many more terminal wrangling recipes can be found in the stty man pages.

Now let’s discuss how stty is used internally during Linux boots and by various system programs…

stty Usage Internally in Linux Systems

In addition to manual shell usage, stty gets used in various places across the Linux boot process and core utilities.

For example many Linux distros invoke stty during early system initialization to stabilize serial consoles. Bootloaders like GRUB will configure the TTY serial port to known-good defaults.

The util-linux project contains stty and uses it for setting up virtual terminals. The binaries /sbin/agetty and /sbin/mingetty rely on stty for opening tty ports with proper line discipline.

So stty gets embedded inside several lower-level Linux system programs.

Additionally communication tools like ssh, screen, and tmux integrate with stty for terminal state management. For example ssh runs stty sane to ensure sane terminal settings on remote sessions.

Debuggers and command-line interfaces also leverage stty for modifying terminal modes during program execution.

So while handy interactively, stty also plays an important role in the Linux toolchain itself.

stty Alternatives: termios, tput

There are a couple alternatives that fill certain niches related to configuring terminals in Linux:

termios – This POSIX system API offers advanced tty configuration from C/C++ code. It provides fine-grained control like stty but requires programming vs command line usage.

tput – Automatically sets terminal capabilities based on the TERM environment variable. Useful for abstracting away terminal-specific codes when designing flexible command-line applications.

However stty itself remains the core tool for direct low-level terminal manipulation from shell scripts or user interactive sessions. It talks directly to the Unix TTY driver, giving you the most power and performance.

Unix/Linux Platform Compatibility

As a core Unix tool dating back to Versions 7 and System III in the 1970s, stty today enjoys broad cross-platform compatibility:

  • Works across all Linux distros including Red Hat, Ubuntu, Debian etc
  • Available on all BSD variants including FreeBSD, OpenBSD, NetBSD
  • Included on commercial Unixes like Solaris, HP-UX, AIX
  • Ships standard on macOS command line tools

So skills mastering stty carry over in any common production or research *nix environment.

The semantics are defined by POSIX standards with only minor behavioral variations between OSes. So stty provides a stable hardware interface for software portability across diverse Unix ecosystems.

Analyzing Performance Implications of stty

Changing stty options can influence terminal speeds, latency, and error rates. For example higher baud rates directly increase serial throughput:

Baud Rate Typical Latency Max Throughput
9600 bps 104 ms per byte 960 bytes/sec
115200 bps 8 ms per byte 11.5 Kbytes/sec
921600 bps 1 ms per byte 90 Kbytes/sec

So for applications like console-based databases or secure shell logins, using the fastest stable baud rate reduces transaction latency.

Adjusting hardware flow control settings can also throttle interface bandwidths. Enabling RTS/CTS prevents buffer overruns but adds round trip latency between 20-500 ms when regulated.

Raw input modes basically eliminate keypress buffer delays for snappier keyboard response.

And sanity resetting with stty sane clears any undesired terminal glitches.

So while not a complete terminal performance suite, stty gives administrators helpful tuning knobs for optimizing speed.

stty Terminal Control for Linux Game Development

To demonstrate using stty in practice, here is an example writing a simple terminal-based game in Linux using C and ncurses:

1. Enter raw mode capturing keyboard scan codes

// Disable canonical input + echo  
system("stty -icanon -echo");

2. Listen on file descriptor 0 for key presses

char keys[5];
int bytes = read(0, keys, 5); // fd 0

3. Detect arrows keys for moving player position

Left arrow = \033[D

Right arrow = \033[C

Up arrow = \033[A

Etc.

4. Reset terminal and exit after game loop finishes

// Restore normal terminal operation
system("stty sane");

This provides a simple example leveraging stty for low-latency input response when developing console-based software.

Conclusion

The stty command remains the best way to access terminal configuration details from the Linux/Unix command line. It manages communication parameters, hardware signals, input modes, output processing, baud rates, and port settings.

Learning to master stty helps optimize terminal latency, increase throughput, resolve hardware issues, build responsive text UIs, analyze performance, and customize shells.

We’ve covered the key syntax options, configuration use cases, internal OS integration, compatibility, tuning tradeoffs, and programming use cases related to stty.

So whether you’re a systems engineer, DevOps expert, platform developer, or IT generalist – knowing your way around stty is essential to fully mastering Linux terminals.

With practice these low-level configuration skills will become second nature. So open up a shell and start sttying around today!

Let us know in the comments if you have any favorite stty tricks or terminal configuration tips.

Similar Posts