1348 Chapter 63
Example program
Listing 63-3 provides a simple example of the use of signal-driven I/O. This program
performs the steps described above for enabling signal-driven I/O on standard
input, and then places the terminal in cbreak mode (Section 62.6.3), so that input is
available a character at a time. The program then enters an infinite loop, perform-
ing the “work” of incrementing a variable, cnt, while waiting for input to become avail-
able. Whenever input becomes available, the SIGIO handler sets a flag, gotSigio, that is
monitored by the main program. When the main program sees that this flag is set, it
reads all available input characters and prints them along with the current value of cnt.
If a hash character (#) is read in the input, the program terminates.
Here is an example of what we see when we run this program and type the x
character a number of times, followed by a hash (#) character:
$ ./demo_sigio
cnt=37; read x
cnt=100; read x
cnt=159; read x
cnt=223; read x
cnt=288; read x
cnt=333; read #
Listing 63-3: Using signal-driven I/O on a terminal
––––––––––––––––––––––––––––––––––––––––––––––––––––––– altio/demo_sigio.c
#include <signal.h>
#include <ctype.h>
#include <fcntl.h>
#include <termios.h>
#include "tty_functions.h" /* Declaration of ttySetCbreak() */
#include "tlpi_hdr.h"
static volatile sig_atomic_t gotSigio = 0;
/* Set nonzero on receipt of SIGIO */
static void
sigioHandler(int sig)
{
gotSigio = 1;
}
int
main(int argc, char *argv[])
{
int flags, j, cnt;
struct termios origTermios;
char ch;
struct sigaction sa;
Boolean done;