home *** CD-ROM | disk | FTP | other *** search
/ Freelog Special Edition 1: Linux / CD1.iso / doc / HOWTO / Serial-Programming-HOWTO < prev    next >
Text File  |  1998-10-14  |  25KB  |  859 lines

  1.   The Linux Serial Programming HOWTO
  2.   by Peter H. Baumann, Peter.Baumann@dlr.de
  3.   v1.0, 22 January 1998
  4.  
  5.   This document describes how to program communications with devices
  6.   over a serial port on a Linux box.
  7.   ______________________________________________________________________
  8.  
  9.   Table of Contents
  10.  
  11.  
  12.   1. Introduction
  13.  
  14.      1.1 Copyright
  15.      1.2 New Versions Of This Document
  16.      1.3 Feedback
  17.  
  18.   2. Getting started
  19.  
  20.      2.1 Debugging
  21.      2.2 Port Settings
  22.      2.3 Input Concepts for Serial Devices
  23.         2.3.1 Canonical Input Processing
  24.         2.3.2 Non-Canonical Input Processing
  25.         2.3.3 Asynchronous Input
  26.         2.3.4 Waiting for Input from Multiple Sources
  27.  
  28.   3. Program Examples
  29.  
  30.      3.1 Canonical Input Processing
  31.      3.2 Non-Canonical Input Processing
  32.      3.3 Asynchronous Input
  33.      3.4 Waiting for Input from Multiple Sources
  34.  
  35.   4. Other Sources of Information
  36.  
  37.   5. Contributions
  38.  
  39.  
  40.  
  41.   ______________________________________________________________________
  42.  
  43.   1.  Introduction
  44.  
  45.   This is the Linux Serial Programming HOWTO.  All about how to program
  46.   communications with other devices / computers over a serial line under
  47.   Linux. Different techniques are explained: Canonical I/O (only
  48.   complete lines are transmitted/received), asyncronous I/O, and waiting
  49.   for input from multiple sources.
  50.  
  51.   This document does not describe how to set up serial ports, because
  52.   this has been described by Greg Hankins in the Serial-HOWTO.
  53.  
  54.   I have to emphasize that I am not an expert in this field, but have
  55.   had problems with a project that involved such communication. The code
  56.   examples presented here were derived from the miniterm code available
  57.   from the LDP programmers guide
  58.   (ftp://sunsite.unc.edu/pub/Linux/docs/LDP/programmers-
  59.   guide/lpg-0.4.tar.gz and mirrors) in the examples directory.
  60.  
  61.   Since I wrote this document in June 1997, I have moved to WinNT to
  62.   satisfy customers need, so I have not built up more in depth
  63.   knowledge. If anybody has any comments, I will gladly incorporate them
  64.   into this document (see sect. Feedback). If someone would like to take
  65.   over and do a better job, please e-mail me.
  66.  
  67.   All examples were tested using a i386 Linux Kernel 2.0.29.
  68.  
  69.  
  70.   1.1.  Copyright
  71.  
  72.   The Linux Serial-Programming-HOWTO is copyright (C) 1997 by Peter
  73.   Baumann.  Linux HOWTO documents may be reproduced and distributed in
  74.   whole or in part, in any medium physical or electronic, as long as
  75.   this copyright notice is retained on all copies. Commercial
  76.   redistribution is allowed and encouraged; however, the author would
  77.   like to be notified of any such distributions.
  78.  
  79.   All translations, derivative works, or aggregate works incorporating
  80.   any Linux HOWTO documents must be covered under this copyright notice.
  81.   That is, you may not produce a derivative work from a HOWTO and impose
  82.   additional restrictions on its distribution. Exceptions to these rules
  83.   may be granted under certain conditions; please contact the Linux
  84.   HOWTO coordinator at the address given below.
  85.  
  86.   In short, we wish to promote dissemination of this information through
  87.   as many channels as possible. However, we do wish to retain copyright
  88.   on the HOWTO documents, and would like to be notified of any plans to
  89.   redistribute the HOWTOs.
  90.  
  91.   If you have questions, please contact Tim Bynum, the Linux HOWTO
  92.   coordinator, at linux-howto@sunsite.unc.edu via email.
  93.  
  94.  
  95.   1.2.  New Versions Of This Document
  96.  
  97.   New versions of the Serial-Programming-HOWTO will be available at
  98.   and mirror sites.  There are other formats, such as PostScript and DVI
  99.   versions in the other-formats directory.  The Serial-Programming-HOWTO
  100.   is also available at http://sunsite.unc.edu/LDP/HOWTO/Serial-
  101.   Programming-HOWTO.html and will be posted to comp.os.linux.answers
  102.   monthly.
  103.  
  104.  
  105.   1.3.  Feedback
  106.  
  107.   Please send me any corrections, questions, comments, suggestions, or
  108.   additional material. I would like to improve this HOWTO!  Tell me
  109.   exactly what you don't understand, or what could be clearer.  You can
  110.   reach me at Peter.Baumann@dlr.de via email. Please include the version
  111.   number of the Serial-Programming-HOWTO when writing, this is version
  112.   0.3.
  113.  
  114.  
  115.  
  116.   2.  Getting started
  117.  
  118.  
  119.   2.1.  Debugging
  120.  
  121.   The best way to debug your code is to set up another Linux box, and
  122.   connect the two computers via a null-modem cable. Use miniterm
  123.   (available from the LDP programmers guide
  124.   (ftp://sunsite.unc.edu/pub/Linux/docs/LDP/programmers-
  125.   guide/lpg-0.4.tar.gz in the examples directory) to transmit characters
  126.   to your Linux box. Miniterm can be compiled very easily and will
  127.   transmit all keyboard input raw over the serial port. Only the define
  128.   statement #define MODEMDEVICE "/dev/ttyS0" has to be checked. Set it
  129.   to ttyS0 for COM1, ttyS1 for COM2, etc.. It is essential for testing,
  130.   that all characters are transmitted raw (without output processing)
  131.   over the line. To test your connection, start miniterm on both
  132.   computers and just type away. The characters input on one computer
  133.   should appear on the other computer and vice versa. The input will not
  134.   be echoed to the attached screen.
  135.  
  136.   To make a null-modem cable you have to cross the TxD (transmit) and
  137.   RxD (receive) lines. For a description of a cable see sect. 7 of the
  138.   Serial-HOWTO.
  139.  
  140.   It is also possible to perform this testing with only one computer, if
  141.   you have two unused serial ports. You can then run two miniterms off
  142.   two virtual consoles. If you free a serial port by disconnecting the
  143.   mouse, remember to redirect /dev/mouse if it exists. If you use a
  144.   multiport serial card, be sure to configure it correctly. I had mine
  145.   configured wrong and everything worked fine as long as I was testing
  146.   only on my computer. When I connected to another computer, the port
  147.   started loosing characters. Executing two programs on one computer
  148.   just isn't fully asynchronous.
  149.  
  150.  
  151.   2.2.  Port Settings
  152.  
  153.   The devices /dev/ttyS* are intended to hook up terminals to your Linux
  154.   box, and are configured for this use after startup. This has to be
  155.   kept in mind when programming communication with a raw device. E.g.
  156.   the ports are configured to echo characters sent from the device back
  157.   to it, which normally has to be changed for data transmission.
  158.  
  159.   All parameters can be easily configured from within a program. The
  160.   configuration is stored in a structure struct termios, which is
  161.   defined in <asm/termbits.h>:
  162.  
  163.  
  164.        #define NCCS 19
  165.        struct termios {
  166.                tcflag_t c_iflag;               /* input mode flags */
  167.                tcflag_t c_oflag;               /* output mode flags */
  168.                tcflag_t c_cflag;               /* control mode flags */
  169.                tcflag_t c_lflag;               /* local mode flags */
  170.                cc_t c_line;                    /* line discipline */
  171.                cc_t c_cc[NCCS];                /* control characters */
  172.        };
  173.  
  174.  
  175.  
  176.  
  177.   This file also includes all flag definitions. The input mode flags in
  178.   c_iflag handle all input processing, which means that the characters
  179.   sent from the device can be processed before they are read with read.
  180.   Similarly c_oflag handles the output processing. c_cflag contains the
  181.   settings for the port, as the baudrate, bits per character, stop bits,
  182.   etc.. The local mode flags stored in c_lflag determine if characters
  183.   are echoed, signals are sent to your program, etc.. Finally the array
  184.   c_cc defines the control characters for end of file, stop, etc..
  185.   Default values for the control characters are defined in
  186.   <asm/termios.h>. The flags are described in the manual page
  187.   termios(3). The structure termios contains the c_line (line
  188.   discipline) element, which is not used in POSIX compliant systems.
  189.  
  190.  
  191.  
  192.   2.3.  Input Concepts for Serial Devices
  193.  
  194.   Here three different input concepts will be presented. The appropriate
  195.   concept has to be chosen for the intended application. Whenever
  196.   possible, do not loop reading single characters to get a complete
  197.   string. When I did this, I lost characters, whereas a read for the
  198.   whole string did not show any errors.
  199.   2.3.1.  Canonical Input Processing
  200.  
  201.   This is the normal processing mode for terminals, but can also be
  202.   useful for communicating with other dl input is processed in units of
  203.   lines, which means that a read will only return a full line of input.
  204.   A line is by default terminated by a NL (ASCII LF), an end of file, or
  205.   an end of line character. A CR (the DOS/Windows default end-of-line)
  206.   will not terminate a line with the default settings.
  207.  
  208.   Canonical input processing can also handle the erase, delete word, and
  209.   reprint characters, translate CR to NL, etc..
  210.  
  211.  
  212.   2.3.2.  Non-Canonical Input Processing
  213.  
  214.   Non-Canonical Input Processing will handle a fixed amount of
  215.   characters per read, and allows for a character timer. This mode
  216.   should be used if your application will always read a fixed number of
  217.   characters, or if the connected device sends bursts of characters.
  218.  
  219.  
  220.  
  221.   2.3.3.  Asynchronous Input
  222.  
  223.   The two modes described above can be used in synchronous and
  224.   asynchronous mode. Synchronous is the default, where a read statement
  225.   will block, until the read is satisfied. In asynchronous mode the read
  226.   statement will return immediatly and send a signal to the calling
  227.   program upon completion. This signal can be received by a signal
  228.   handler.
  229.  
  230.  
  231.   2.3.4.  Waiting for Input from Multiple Sources
  232.  
  233.   This is not a different input mode, but might be useful, if you are
  234.   handling multiple devices. In my application I was handling input over
  235.   a TCP/IP socket and input over a serial connection from another
  236.   computer quasi-simultaneously. The program example given below will
  237.   wait for input from two different input sources. If input from one
  238.   source becomes available, it will be processed, and the program will
  239.   then wait for new input.
  240.  
  241.   The approach presented below seems rather complex, but it is important
  242.   to keep in mind that Linux is a multi-processing operating system. The
  243.   select system call will not load the CPU while waiting for input,
  244.   whereas looping until input becomes available would slow down other
  245.   processes executing at the same time.
  246.  
  247.  
  248.  
  249.   3.  Program Examples
  250.  
  251.   All examples have been derived from miniterm.c. The type ahead buffer
  252.   is limited to 255 characters, just like the maximum string length for
  253.   canonical input processing (<linux/limits.h> or <posix1_lim.h>).
  254.  
  255.   See the comments in the code for explanation of the use of the
  256.   different input modes. I hope that the code is understandable. The
  257.   example for canonical input is commented best, the other examples are
  258.   commented only where they differ from the example for canonical input
  259.   to emphasize the differences.
  260.  
  261.   The descriptions are not complete, but you are encouraged to
  262.   experiment with the examples to derive the best solution for your
  263.   application.
  264.  
  265.   Don't forget to give the appropriate serial ports the right
  266.   permissions (e. g.: chmod a+rw /dev/ttyS1)!
  267.  
  268.  
  269.  
  270.   3.1.  Canonical Input Processing
  271.  
  272.  
  273.  
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
  280.  
  281.  
  282.  
  283.  
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293.  
  294.  
  295.  
  296.  
  297.  
  298.  
  299.  
  300.  
  301.  
  302.  
  303.  
  304.  
  305.  
  306.  
  307.  
  308.  
  309.  
  310.  
  311.  
  312.  
  313.  
  314.  
  315.  
  316.  
  317.  
  318.  
  319.  
  320.  
  321.  
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.   #include <sys/types.h>
  332.   #include <sys/stat.h>
  333.   #include <fcntl.h>
  334.   #include <termios.h>
  335.   #include <stdio.h>
  336.  
  337.   /* baudrate settings are defined in <asm/termbits.h>, which is
  338.   included by <termios.h> */
  339.   #define BAUDRATE B38400
  340.   /* change this definition for the correct port */
  341.   #define MODEMDEVICE "/dev/ttyS1"
  342.   #define _POSIX_SOURCE 1 /* POSIX compliant source */
  343.  
  344.   #define FALSE 0
  345.   #define TRUE 1
  346.  
  347.   volatile int STOP=FALSE;
  348.  
  349.   main()
  350.   {
  351.     int fd,c, res;
  352.     struct termios oldtio,newtio;
  353.     char buf[255];
  354.   /*
  355.     Open modem device for reading and writing and not as controlling tty
  356.     because we don't want to get killed if linenoise sends CTRL-C.
  357.   */
  358.    fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
  359.    if (fd <0) {perror(MODEMDEVICE); exit(-1); }
  360.  
  361.    tcgetattr(fd,&oldtio); /* save current serial port settings */
  362.    bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
  363.  
  364.   /*
  365.     BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
  366.     CRTSCTS : output hardware flow control (only used if the cable has
  367.               all necessary lines. See sect. 7 of Serial-HOWTO)
  368.     CS8     : 8n1 (8bit,no parity,1 stopbit)
  369.     CLOCAL  : local connection, no modem contol
  370.     CREAD   : enable receiving characters
  371.   */
  372.    newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  373.  
  374.   /*
  375.     IGNPAR  : ignore bytes with parity errors
  376.     ICRNL   : map CR to NL (otherwise a CR input on the other computer
  377.               will not terminate input)
  378.     otherwise make device raw (no other input processing)
  379.   */
  380.    newtio.c_iflag = IGNPAR | ICRNL;
  381.  
  382.   /*
  383.    Raw output.
  384.   */
  385.    newtio.c_oflag = 0;
  386.  
  387.   /*
  388.     ICANON  : enable canonical input
  389.     disable all echo functionality, and don't send signals to calling program
  390.   */
  391.    newtio.c_lflag = ICANON;
  392.  
  393.   /*
  394.     initialize all control characters
  395.     default values can be found in /usr/include/termios.h, and are given
  396.     in the comments, but we don't need them here
  397.   */
  398.    newtio.c_cc[VINTR]    = 0;     /* Ctrl-c */
  399.    newtio.c_cc[VQUIT]    = 0;     /* Ctrl-\ */
  400.    newtio.c_cc[VERASE]   = 0;     /* del */
  401.    newtio.c_cc[VKILL]    = 0;     /* @ */
  402.    newtio.c_cc[VEOF]     = 4;     /* Ctrl-d */
  403.    newtio.c_cc[VTIME]    = 0;     /* inter-character timer unused */
  404.    newtio.c_cc[VMIN]     = 1;     /* blocking read until 1 character arrives */
  405.    newtio.c_cc[VSWTC]    = 0;     /* '\0' */
  406.    newtio.c_cc[VSTART]   = 0;     /* Ctrl-q */
  407.    newtio.c_cc[VSTOP]    = 0;     /* Ctrl-s */
  408.    newtio.c_cc[VSUSP]    = 0;     /* Ctrl-z */
  409.    newtio.c_cc[VEOL]     = 0;     /* '\0' */
  410.    newtio.c_cc[VREPRINT] = 0;     /* Ctrl-r */
  411.    newtio.c_cc[VDISCARD] = 0;     /* Ctrl-u */
  412.    newtio.c_cc[VWERASE]  = 0;     /* Ctrl-w */
  413.    newtio.c_cc[VLNEXT]   = 0;     /* Ctrl-v */
  414.    newtio.c_cc[VEOL2]    = 0;     /* '\0' */
  415.  
  416.   /*
  417.     now clean the modem line and activate the settings for the port
  418.   */
  419.    tcflush(fd, TCIFLUSH);
  420.    tcsetattr(fd,TCSANOW,&newtio);
  421.  
  422.   /*
  423.     terminal settings done, now handle input
  424.     In this example, inputting a 'z' at the beginning of a line will
  425.     exit the program.
  426.   */
  427.    while (STOP==FALSE) {     /* loop until we have a terminating condition */
  428.    /* read blocks program execution until a line terminating character is
  429.       input, even if more than 255 chars are input. If the number
  430.       of characters read is smaller than the number of chars available,
  431.       subsequent reads will return the remaining chars. res will be set
  432.       to the actual number of characters actually read */
  433.       res = read(fd,buf,255);
  434.       buf[res]=0;             /* set end of string, so we can printf */
  435.       printf(":%s:%d\n", buf, res);
  436.       if (buf[0]=='z') STOP=TRUE;
  437.    }
  438.    /* restore the old port settings */
  439.    tcsetattr(fd,TCSANOW,&oldtio);
  440.   }
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.   3.2.  Non-Canonical Input Processing
  448.  
  449.   In non-canonical input processing mode, input is not assembled into
  450.   lines and input processing (erase, kill, delete, etc.) does not occur.
  451.   Two parameters control the behavior of this mode: c_cc[VTIME] sets the
  452.   character timer, and c_cc[VMIN] sets the minimum number of characters
  453.   to receive before satisfying the read.
  454.  
  455.   If MIN > 0 and TIME = 0, MIN sets the number of characters to receive
  456.   before the read is satisfied. As TIME is zero, the timer is not used.
  457.  
  458.   If MIN = 0 and TIME > 0, TIME serves as a timeout value. The read will
  459.   be satisfied if a single character is read, or TIME is exceeded (t =
  460.   TIME *0.1 s). If TIME is exceeded, no character will be returned.
  461.  
  462.  
  463.   If MIN > 0 and TIME > 0, TIME serves as an inter-character timer. The
  464.   read will be satisfied if MIN characters are received, or the time
  465.   between two characters exceeds TIME. The timer is restarted every time
  466.   a character is received and only becomes active after the first
  467.   character has been received.
  468.  
  469.   If MIN = 0 and TIME = 0, read will be satisfied immediately. The
  470.   number of characters currently available, or the number of characters
  471.   requested will be returned. According to Antonino (see contributions),
  472.   you could issue a fcntl(fd, F_SETFL, FNDELAY); before reading to get
  473.   the same result.
  474.  
  475.   By modifying newtio.c_cc[VTIME] and newtio.c_cc[VMIN] all modes
  476.   described above can be tested.
  477.  
  478.  
  479.  
  480.        #include <sys/types.h>
  481.        #include <sys/stat.h>
  482.        #include <fcntl.h>
  483.        #include <termios.h>
  484.        #include <stdio.h>
  485.  
  486.        #define BAUDRATE B38400
  487.        #define MODEMDEVICE "/dev/ttyS1"
  488.        #define _POSIX_SOURCE 1 /* POSIX compliant source */
  489.        #define FALSE 0
  490.        #define TRUE 1
  491.  
  492.        volatile int STOP=FALSE;
  493.  
  494.        main()
  495.        {
  496.          int fd,c, res;
  497.          struct termios oldtio,newtio;
  498.          char buf[255];
  499.  
  500.         fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
  501.         if (fd <0) {perror(MODEMDEVICE); exit(-1); }
  502.  
  503.         tcgetattr(fd,&oldtio); /* save current port settings */
  504.  
  505.         bzero(&newtio, sizeof(newtio));
  506.         newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  507.         newtio.c_iflag = IGNPAR;
  508.         newtio.c_oflag = 0;
  509.  
  510.         /* set input mode (non-canonical, no echo,...) */
  511.         newtio.c_lflag = 0;
  512.  
  513.         newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
  514.         newtio.c_cc[VMIN]     = 5;   /* blocking read until 5 chars received */
  515.  
  516.         tcflush(fd, TCIFLUSH);
  517.         tcsetattr(fd,TCSANOW,&newtio);
  518.  
  519.  
  520.         while (STOP==FALSE) {       /* loop for input */
  521.           res = read(fd,buf,255);   /* returns after 5 chars have been input */
  522.           buf[res]=0;               /* so we can printf... */
  523.           printf(":%s:%d\n", buf, res);
  524.           if (buf[0]=='z') STOP=TRUE;
  525.         }
  526.         tcsetattr(fd,TCSANOW,&oldtio);
  527.        }
  528.  
  529.   3.3.  Asynchronous Input
  530.  
  531.  
  532.  
  533.  
  534.  
  535.  
  536.  
  537.  
  538.  
  539.  
  540.  
  541.  
  542.  
  543.  
  544.  
  545.  
  546.  
  547.  
  548.  
  549.  
  550.  
  551.  
  552.  
  553.  
  554.  
  555.  
  556.  
  557.  
  558.  
  559.  
  560.  
  561.  
  562.  
  563.  
  564.  
  565.  
  566.  
  567.  
  568.  
  569.  
  570.  
  571.  
  572.  
  573.  
  574.  
  575.  
  576.  
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.  
  592.  
  593.  
  594.  
  595.   #include <termios.h>
  596.   #include <stdio.h>
  597.   #include <unistd.h>
  598.   #include <fcntl.h>
  599.   #include <sys/signal.h>
  600.   #include <sys/types.h>
  601.  
  602.   #define BAUDRATE B38400
  603.   #define MODEMDEVICE "/dev/ttyS1"
  604.   #define _POSIX_SOURCE 1 /* POSIX compliant source */
  605.   #define FALSE 0
  606.   #define TRUE 1
  607.  
  608.   volatile int STOP=FALSE;
  609.  
  610.   void signal_handler_IO (int status);   /* definition of signal handler */
  611.   int wait_flag=TRUE;                    /* TRUE while no signal received */
  612.  
  613.   main()
  614.   {
  615.     int fd,c, res;
  616.     struct termios oldtio,newtio;
  617.     struct sigaction saio;           /* definition of signal action */
  618.     char buf[255];
  619.  
  620.     /* open the device to be non-blocking (read will return immediatly) */
  621.     fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
  622.     if (fd <0) {perror(MODEMDEVICE); exit(-1); }
  623.  
  624.     /* install the signal handler before making the device asynchronous */
  625.     saio.sa_handler = signal_handler_IO;
  626.     saio.sa_mask = 0;
  627.     saio.sa_flags = 0;
  628.     saio.sa_restorer = NULL;
  629.     sigaction(SIGIO,&saio,NULL);
  630.  
  631.     /* allow the process to receive SIGIO */
  632.     fcntl(fd, F_SETOWN, getpid());
  633.     /* Make the file descriptor asynchronous (the manual page says only
  634.        O_APPEND and O_NONBLOCK, will work with F_SETFL...) */
  635.     fcntl(fd, F_SETFL, FASYNC);
  636.  
  637.     tcgetattr(fd,&oldtio); /* save current port settings */
  638.     /* set new port settings for canonical input processing */
  639.     newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  640.     newtio.c_iflag = IGNPAR | ICRNL;
  641.     newtio.c_oflag = 0;
  642.     newtio.c_lflag = ICANON;
  643.     newtio.c_cc[VMIN]=1;
  644.     newtio.c_cc[VTIME]=0;
  645.     tcflush(fd, TCIFLUSH);
  646.     tcsetattr(fd,TCSANOW,&newtio);
  647.  
  648.     /* loop while waiting for input. normally we would do something
  649.        useful here */
  650.     while (STOP==FALSE) {
  651.       printf(".\n");usleep(100000);
  652.       /* after receiving SIGIO, wait_flag = FALSE, input is available
  653.          and can be read */
  654.       if (wait_flag==FALSE) {
  655.         res = read(fd,buf,255);
  656.         buf[res]=0;
  657.         printf(":%s:%d\n", buf, res);
  658.         if (res==1) STOP=TRUE; /* stop loop if only a CR was input */
  659.         wait_flag = TRUE;      /* wait for new input */
  660.       }
  661.     }
  662.     /* restore old port settings */
  663.     tcsetattr(fd,TCSANOW,&oldtio);
  664.   }
  665.  
  666.   /***************************************************************************
  667.   * signal handler. sets wait_flag to FALSE, to indicate above loop that     *
  668.   * characters have been received.                                           *
  669.   ***************************************************************************/
  670.  
  671.   void signal_handler_IO (int status)
  672.   {
  673.     printf("received SIGIO signal.\n");
  674.     wait_flag = FALSE;
  675.   }
  676.  
  677.  
  678.  
  679.  
  680.  
  681.   3.4.  Waiting for Input from Multiple Sources
  682.  
  683.   This section is kept to a minimum. It is just intended to be a hint,
  684.   and therefore the example code is kept short. This will not only work
  685.   with serial ports, but with any set of file descriptors.
  686.  
  687.   The select call and accompanying macros use a fd_set. This is a bit
  688.   array, which has a bit entry for every valid file descriptor number.
  689.   select will accept a fd_set with the bits set for the relevant file
  690.   descriptors and returns a fd_set, in which the bits for the file
  691.   descriptors are set where input, output, or an exception occurred. All
  692.   handling of fd_set is done with the provided macros. See also the
  693.   manual page select(2).
  694.  
  695.  
  696.  
  697.  
  698.  
  699.  
  700.  
  701.  
  702.  
  703.  
  704.  
  705.  
  706.  
  707.  
  708.  
  709.  
  710.  
  711.  
  712.  
  713.  
  714.  
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.  
  724.  
  725.  
  726.  
  727.   #include <sys/time.h>
  728.   #include <sys/types.h>
  729.   #include <unistd.h>
  730.  
  731.   main()
  732.   {
  733.      int    fd1, fd2;  /* input sources 1 and 2 */
  734.      fd_set readfs;    /* file descriptor set */
  735.      int    maxfd;     /* maximum file desciptor used */
  736.      int    loop=1;    /* loop while TRUE */
  737.  
  738.      /* open_input_source opens a device, sets the port correctly, and
  739.         returns a file descriptor */
  740.      fd1 = open_input_source("/dev/ttyS1");   /* COM2 */
  741.      if (fd1<0) exit(0);
  742.      fd2 = open_input_source("/dev/ttyS2");   /* COM3 */
  743.      if (fd2<0) exit(0);
  744.      maxfd = MAX (fd1, fd2)+1;  /* maximum bit entry (fd) to test */
  745.  
  746.      /* loop for input */
  747.      while (loop) {
  748.        FD_SET(fd1, &readfs);  /* set testing for source 1 */
  749.        FD_SET(fd2, &readfs);  /* set testing for source 2 */
  750.        /* block until input becomes available */
  751.        select(maxfd, &readfs, NULL, NULL, NULL);
  752.        if (FD_ISSET(fd1))         /* input from source 1 available */
  753.          handle_input_from_source1();
  754.        if (FD_ISSET(fd2))         /* input from source 2 available */
  755.          handle_input_from_source2();
  756.      }
  757.  
  758.   }
  759.  
  760.  
  761.  
  762.  
  763.   The given example blocks indefinitely, until input from one of the
  764.   sources becomes available. If you need to timeout on input, just
  765.   replace the select call by:
  766.  
  767.  
  768.        int res;
  769.        struct timeval Timeout;
  770.  
  771.        /* set timeout value within input loop */
  772.        Timeout.tv_usec = 0;  /* milliseconds */
  773.        Timeout.tv_sec  = 1;  /* seconds */
  774.        res = select(maxfd, &readfs, NULL, NULL, &Timeout);
  775.        if (res==0)
  776.        /* number of file descriptors with input = 0, timeout occurred. */
  777.  
  778.  
  779.  
  780.  
  781.   This example will timeout after 1 second. If a timeout occurs, select
  782.   will return 0, but beware that Timeout is decremented by the time
  783.   actually waited for input by select. If the timeout value is zero,
  784.   select will return immediatly.
  785.  
  786.  
  787.  
  788.   4.  Other Sources of Information
  789.  
  790.  
  791.  
  792.  
  793.   o  The Linux Serial-HOWTO describes how to set up serial ports and
  794.      contains hardware information.
  795.  
  796.   o  Serial Programming Guide for POSIX Compliant Operating Systems
  797.      <http://www.easysw.com/~mike/serial>, by Michael Sweet. This link
  798.      is obsolete and I could not find a new location for it. Does
  799.      somebody know where we can find it again? It was a well prepared
  800.      document!
  801.  
  802.   o  The manual page termios(3) describes all flags for the termios
  803.      structure.
  804.  
  805.  
  806.   5.  Contributions
  807.  
  808.  
  809.   As mentioned in the introduction, I am no expert in this field, but
  810.   had problems myself, and found a solution with the help of others.
  811.   Thanks for the help from Mr. Strudthoff from the European Transonic
  812.   Windtunnel, Cologne, Michael Carter (mcarter@rocke.electro.swri.edu,
  813.   and Peter Waltenberg (p.waltenberg@karaka.chch.cri.nz)
  814.  
  815.  
  816.   Antonino Ianella (antonino@usa.net wrote the Serial-Port-Programming
  817.   Mini HOWTO, at the same time I prepared this document. Greg Hankins
  818.   asked me to incorporate Antonino's Mini-HOWTO into this document.
  819.  
  820.  
  821.   The structure of this document and SGML formatting was derived from
  822.   the Serial-HOWTO by Greg Hankins. Thanks also for various corrections
  823.   made by : Dave Pfaltzgraff (Dave_Pfaltzgraff@patapsco.com), Sean
  824.   Lincolne (slincol@tpgi.com.au), Michael Wiedmann (mw@miwie.in-
  825.   berlin.de), and Adrey Bonar (andy@tipas.lt).
  826.  
  827.  
  828.  
  829.  
  830.  
  831.  
  832.  
  833.  
  834.  
  835.  
  836.  
  837.  
  838.  
  839.  
  840.  
  841.  
  842.  
  843.  
  844.  
  845.  
  846.  
  847.  
  848.  
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.  
  856.  
  857.  
  858.  
  859.