Getting and Setting Terminal Attributes
To get and set a termios structure, we call two functions: tcgetattr and tcsetattr. This is how we examine and modify the various option flags and special characters to make the terminal operate the way we want it to.
#include <termios.h>
int tcgetattr(int fd, struct termios *termptr);
int tcsetattr(int fd, int opt, const struct termios *termptr);
Terminal Option Flags
#include "apue.h"
#include <termios.h>
int main(void)
{
struct termios term;
if(tcgetattr(STDIN_FILENO, &term)<0)
err_sys("tcgetattr error");
switch(term.c_cflag& CSIZE)
{
case CS5:
printf("5 bits/byte\n");
break;
case CS6:
printf("6 bits/byte\n");
break;
case CS7:
printf("7 bits/byte\n");
break;
case CS8:
printf("8 bits/byte\n");
break;
default:
printf("unknown bits/byte\n");
}
term.c_cflag&=~CSIZE;
term.c_flag|=CS8;
if(tcsetattr(STDIN_FILENO, TCSANOW, &term)<0)
err_sys("tcsetattr error");
return 0;
}
Example of tcgetattr and tcsetattr
You should take references to learn more details about each of the flags.
stty Command
All the options described in the previous section can be examined and changed from within a program with the tcgetattr and tcsetattr functions (Section 18.4) or from the command line (or a shell script) with the stty(1) command. This command is simply an interface to the first six functions that we listed in Figure 18.7. If we execute this command with its -a option, it displays all the terminal options.
The stty command uses its standard input to get and set the terminal option flags. Although some older implementations used standard output, POSIX.1 requires that the standard input be used. All four implementations discussed in this text provide versions of stty that operate on the standard input. This means that we can type
stty -a </dev/tty1a
if we are interested in discovering the settings on the terminal named tty1a.
Baud Rate Functions
The term baud rate is a historical term that should be referred to today as ‘‘bits per second.’’ Although most terminal devices use the same baud rate for both input and output, the capability exists to set the two rates to different values, if the hardware allows this.
#include <termios.h>
speed_t cfgetispeed(const struct termios *termptr);
speed_t cfgetospeed(const struct termios *termptr);
int cfsetispeed(struct termios *termptr, speed_t speed);
int cfsetospeed(struct termios *termptr, speed_t speed);
Line Control Functions
The following four functions provide line control capability for terminal devices. All four require that fd refer to a terminal device; otherwise, −1 is returned with errno set to ENOTTY.
#include <termios.h>
int tcdrain(int fd);
int tcflow(int fd, int action);
int tcflush(int fd, int queue);
int tcsendbreak(int fd, int duration);