The Linux Programming Interface

(nextflipdebug5) #1

1310 Chapter 62


settings). Cbreak mode did not disable echoing, but applications employing this
mode would usually disable echoing as well. Cbreak mode was useful in screen-
handling applications (such as less) that permitted character-by-character input, but
still needed to allow interpretation of characters such as INTR, QUIT, and SUSP.

Example: setting raw and cbreak mode
In the Seventh Edition and the original BSD terminal drivers, it was possible to
switch to raw or cbreak mode by tweaking single bits (called RAW and CBREAK) in the
terminal driver data structures. With the transition to the POSIX termios interface
(now supported on all UNIX implementations), single bits for selecting raw and
cbreak mode are no longer available, and applications emulating these modes must
explicitly change the required fields of the termios structure. Listing 62-3 provides
two functions, ttySetCbreak() and ttySetRaw(), that implement the equivalents of
these terminal modes.

Applications that use the ncurses library can call the functions cbreak() and
raw(), which perform similar tasks to our functions in Listing 62-3.

Listing 62-3: Switching a terminal to cbreak and raw modes
–––––––––––––––––––––––––––––––––––––––––––––––––––––––tty/tty_functions.c
#include <termios.h>
#include <unistd.h>
#include "tty_functions.h" /* Declares functions defined here */

/* Place terminal referred to by 'fd' in cbreak mode (noncanonical mode
with echoing turned off). This function assumes that the terminal is
currently in cooked mode (i.e., we shouldn't call it if the terminal
is currently in raw mode, since it does not undo all of the changes
made by the ttySetRaw() function below). Return 0 on success, or -1
on error. If 'prevTermios' is non-NULL, then use the buffer to which
it points to return the previous terminal settings. */

int
ttySetCbreak(int fd, struct termios *prevTermios)
{
struct termios t;

if (tcgetattr(fd, &t) == -1)
return -1;

if (prevTermios != NULL)
*prevTermios = t;

t.c_lflag &= ~(ICANON | ECHO);
t.c_lflag |= ISIG;

t.c_iflag &= ~ICRNL;
Free download pdf