1
Downloaded from http://www.lafn.org/~dave/linux/Serial-Programming-HOWTO.txt
2
Seems to be somewhat old, but contains useful bits for getty.c hacking
3
============================================================================
5
The Linux Serial Programming HOWTO, Part 1 of 2
9
This document describes how to program communications with devices
10
over a serial port on a Linux box.
11
______________________________________________________________________
23
5. Changing Baud Rates
25
6. Additional Control Calls
27
6.1 Sending a "break".
28
6.2 Hardware flow control.
29
6.3 Flushing I/O buffers.
37
8.3 Controlling Terminal
38
8.3.1 Get the foreground group process id.
39
8.3.2 Set the foreground process group id of a terminal.
40
8.3.3 Get process group id.
44
10. Additional Information
48
______________________________________________________________________
52
The Linux Serial-Programming-HOWTO is copyright (C) 1997 by Vernon
53
Hoxie. Linux HOWTO documents may be reproduced and distributed in
54
whole or in part, in any medium physical or electronic, as long as
55
this copyright notice is retained on all copies. Commercial
56
redistribution is allowed and encouraged; however, the author would
57
like to be notified of any such distributions.
59
All translations, derivative works, or aggregate works incorporating
60
this Linux HOWTO document must be covered under this copyright notice.
61
That is, you may not produce a derivative work from this HOWTO and
62
impose additional restrictions on its distribution.
64
This version is a complete rewrite of the previous Serial-Programming-
65
HOWTO by Peter H. Baumann, <mailto:Peter.Baumann@dlr.de>
69
This HOWTO will attempt to give hints about how to write a program
70
which needs to access a serial port. Its principal focus will be on
71
the Linux implementation and what the meaning of the various library
74
Someone asked about which of several sequences of operations was
75
right. There is no absolute right way to accomplish an outcome. The
76
options available are too numerous. If your sequences produces the
77
desired results, then that is the right way for you. Another
78
programmer may select another set of options and get the same results.
79
His method is right for him.
81
Neither of these methods may operate properly with some other
82
implementation of UNIX. It is strange that many of the concepts which
83
were implemented in the SYSV version have been dumped. Because UNIX
84
was developed by AT&T and much code has been generated on those
85
concepts, the AT&T version should be the standard to which others
88
Now the standard is POSIX.
90
It was once stated that the popularity of UNIX and C was that they
91
were created by programmers for programmers. Not by scholars who
92
insist on purity of style in deference to results and simplicity of
93
use. Not by committees with people who have diverse personal or
94
proprietary agenda. Now ANSI and POSIX have strayed from those
95
original clear and simply concepts.
99
The various serial devices are opened just as any other file.
100
Although, the fopen(3) command may be used, the plain open(2) is
101
preferred. This call returns the file descriptor which is required
102
for the various commands that configure the interface.
104
Open(2) has the format:
107
int open(char *path, int flags, [int mode]);
109
In addition to the obvious O_RDWR, O_WRONLY and O_RDONLY, two
110
additional flags are available. These are O_NONBLOCK and O_NOCTTY.
111
Other flags listed in the open(2) manual page are not applicable to
114
Normally, a serial device opens in "blocking" mode. This means that
115
the open() will not return until the Carrier Detect line from the port
116
is active, e.g. modem, is active. When opened with the O_NONBLOCK
117
flag set, the open() will return immediately regardless of the status
118
of the DCD line. The "blocking" mode also affects the read() call.
120
The fcntl(2) command can be used to change the O_NONBLOCK flag anytime
121
after the device has been opened.
123
The device driver and the data passing through it are controlled
124
according to settings in the struct termios. This structure is
125
defined in "/usr/include/termios.h". In the Linux tree, further
126
reference is made to "/usr/include/asm/termbits.h".
127
In blocking mode, a read(2) will block until data is available or a
128
signal is received. It is still subject to state of the ICANON flag.
130
When the termios.c_lflag ICANON bit is set, input data is collected
131
into strings until a NL, EOF or EOL character is received. You can
132
define these in the termios.c_cc[] array. Also, ERASE and KILL
133
characters will operate on the incoming data before it is delivered to
136
In non-canonical mode, incoming data is quantified by use of the
137
c_cc[VMIN and c_cc[VTIME] values in termios.c_cc[].
139
Some programmers use the select() call to detect the completion of a
140
read(). This is not the best way of checking for incoming data.
141
Select() is part of the SOCKETS scheme and too complex for most
144
A full explanation of the fields of the termios structure is contained
145
in termios(7) of the Users Manual. A version is included in Part 2 of
150
Changes to the struct termios are made by retrieving the current
151
settings, making the desired changes and transmitting the modified
152
structure back to the kernel.
154
The historic means of communicating with the kernel was by use of the
155
ioctl(fd, COMMAND, arg) system call. Then the purists in the
156
computer industry decided that this was not genetically consistent.
157
Their argument was that the argument changed its stripes. Sometimes
158
it was an int, sometimes it was a pointer to int and other times it
159
was a pointer to struct termios. Then there were those times it was
160
empty or NULL. These variations are dependent upon the COMMAND.
162
As a alternative, the tc* series of functions were concocted.
166
int tcgetattr(int filedes, struct termios *termios_p);
167
int tcsetattr(int filedes, int optional_actions,
168
const struct termios *termios_p);
172
int ioctl(int filedes, int command,
173
struct termios *termios_p);
175
where command is TCGETS or one of TCSETS, TCSETSW or TCSETSF.
177
The TCSETS command is comparable to the TCSANOW optional_action for
178
the tc* version. These direct the kernel to adopt the changes
179
immediately. Other pairs are:
181
command optional_action Meaning
182
TCSETSW TCSADRAIN Change after all output has drained.
183
TCSETSF TCSAFLUSH Change after all output has drained
184
then discard any input characters
187
Since the return code from either the ioctl(2) or the tcsetattr(2)
188
commands only indicate that the command was processed by the kernel.
189
These do not indicate whether or not the changes were actually
190
accomplished. Either of these commands should be followed by a call
193
ioctl(fd, TCGETS, &new_termios);
197
tcgetattr(fd, &new_termios);
199
A user function which makes changes to the termios structure should
200
define two struct termios variables. One of these variables should
201
contain the desired configuration. The other should contain a copy of
202
the kernels version. Then after the desired configuration has been
203
sent to the kernel, another call should be made to retrieve the
204
kernels version. Then the two compared.
206
Here is an example of how to add RTS/CTS flow control:
208
struct termios my_termios;
209
struct termios new_termios;
211
tcgetattr(fd, &my_termios);
212
my_termios.c_flag |= CRTSCTS;
213
tcsetattr(fd, TCSANOW, &my_termios);
214
tcgetattr(fd, &new_termios);
215
if (memcmp(my_termios, new_termios,
216
sizeof(my_termios)) != 0) {
217
/* do some error handling */
220
5. Changing Baud Rates
222
With Linux, the baud rate can be changed using a technique similar to
225
struct termios my_termios;
226
struct termios new_termios;
228
tcgetattr(fd, &my_termios);
229
my_termios.c_flag &= ~CBAUD;
230
my_termios.c_flag |= B19200;
231
tcsetattr(fd, TCSANOW, &my_termios);
232
tcgetattr(fd, &new_termios);
233
if (memcmp(my_termios, new_termios,
234
sizeof(my_termios)) != 0) {
235
/* do some error handling */
238
POSIX adds another method. They define:
240
speed_t cfgetispeed(const struct termios *termios_p);
241
speed_t cfgetospeed(const struct termios *termios_p);
243
library calls to extract the current input or output speed from the
244
struct termios pointed to with *termio_p. This is a variable defined
245
in the calling process. In practice, the data contained in this
246
termios, should be obtained by the tcgetattr() call or an ioctl() call
247
using the TCGETS command.
249
The companion library calls are:
251
int cfsetispeed(struct termios *termios_p, speed_t speed);
252
int cfsetospeed(struct termios *termios_p, speed_t speed);
254
which are used to change the value of the baud rate in the locally
255
defined *termios_p. Following either of these calls, either a call to
256
tcsetattr() or ioctl() with one of TCSETS, TCSETSW or TCSETSF as the
257
command to transmit the change to the kernel.
259
The cf* commands are preferred for portability. Some weird Unices use
260
a considerably different format of termios.
262
Most implementations of Linux use only the input speed for both input
263
and output. These functions are defined in the application program by
264
reference to <termios.h>. In reality, they are in
265
/usr/include/asm/termbits.h.
267
6. Additional Control Calls
269
6.1. Sending a "break".
271
int ioctl(fd, TCSBRK, int arg);
272
int tcsendbreak(fd, int arg);
274
Send a break: Here the action differs between the conventional
275
ioctl() call and the POSIX call. For the conventional call, an arg of
276
'0' sets the break control line of the UART for 0.25 seconds. For the
277
POSIX command, the break line is set for arg times 0.1 seconds.
279
6.2. Hardware flow control.
281
int ioctl(fd, TCXONC, int action);
282
int tcflow(fd, int action);
284
The action flags are:
286
o TCOOFF 0 suspend output
288
o TCOON 1 restart output
290
o TCIOFF 2 transmit STOP character to suspend input
292
o TCION 3 transmit START character to restart input
294
6.3. Flushing I/O buffers.
296
int ioctl(fd, TCFLSH, queue_selector);
297
int tcflush(fd, queue_selector);
299
The queue_selector flags are:
301
o TCIFLUSH 0 flush any data not yet read from the input buffer
303
o TCOFLUSH 1 flush any data written to the output buffer but not
306
o TCIOFLUSH 2 flush both buffers
310
The hardware modem control lines can be monitored or modified by the
311
ioctl(2) system call. A set of comparable tc* calls apparently do not
312
exist. The form of this call is:
314
int ioctl(fd, COMMAND, (int *)flags);
316
The COMMANDS and their action are:
318
o TIOCMBIS turn on control lines depending upon which bits are set
321
o TIOCMBIC turn off control lines depending upon which bits are
323
o TIOCMGET the appropriate bits are set in flags according to the
326
o TIOCMSET the state of the UART is changed according to which bits
327
are set/unset in 'flags'
329
The bit pattern of flags refer to the following control lines:
331
o TIOCM_LE Line enable
333
o TIOCM_DTR Data Terminal Ready
335
o TIOCM_RTS Request to send
337
o TIOCM_ST Secondary transmit
339
o TIOCM_SR Secondary receive
341
o TIOCM_CTS Clear to send
343
o TIOCM_CAR Carrier detect
347
o TIOCM_DSR Data set ready
349
It should be noted that some of these bits are controlled by the modem
350
and the UART cannot change them but their status can be sensed by
351
TIOCMGET. Also, most Personal Computers do not provide hardware for
352
secondary transmit and receive.
354
There are also a pair of ioctl() to monitor these lines. They are
355
undocumented as far as I have learned. The commands are TIOCMIWAIT
356
and TCIOGICOUNT. They also differ between versions of the Linux
359
See the lines.c file in my "serial_suite" for an example of how these
360
can be used see <ftp://scicom.alphacd.com/pub/linux/serial_suite>
368
Any newly created process inherits the Process Group of its creator.
369
The Process Group leader has the same PID as PGID.
371
8.3. Controlling Terminal
373
There are a series of ioctl(2) and tc*(2) calls which can be used to
374
monitor or to change the process group to which the device is
377
8.3.1. Get the foreground group process id.
379
If there is no foreground group, a number not representing an existing
380
process group is returned. On error, a -1 is returned and errno is
383
int ioctl(fd, TIOCGPGRP, (pid_t *)pid);
384
int tcgetpgrp(fd, (pid_t *)pid);
386
8.3.2. Set the foreground process group id of a terminal.
388
The fd must be the controlling terminal and be associated with the
389
session of the calling process.
391
int ioctl(fd, TIOCSPGRP, (pid_t *)pid);
392
int tcsetpgrp(fd, (pid_t *)pid);
394
8.3.3. Get process group id.
396
int ioctl(fd, TIOCGPGRP, &(pid_t)pid);
397
int tcgetpgrp(fd, &(pid_t)pid);
401
Any process which accesses a serial device should first check for the
402
existence of lock file for the desired device. If such a lock lock
403
file exists, this means that the device may be in use by another
406
Check my "libdevlocks-x.x.tgz" at
407
<ftp://scicom.alphacdc.com/pub/linux> for an example of how these lock
408
files should be utilized.
410
10. Additional Information
412
Check out my "serial_suite.tgz" for more information about programming
413
the serial ports at <mailto:vern@zebra.alphacdc.com>. There some
414
examples and some blurbs about setting up modems and comments about
415
some general considerations.
419
Please send me any corrections, questions, comments, suggestions, or
420
additional material. I would like to improve this HOWTO! Tell me
421
exactly what you don't understand, or what could be clearer. You can
422
reach me at <mailto:vern@zebra.alphacdc.com> via email. Please
423
include the version number of the Serial-Programming-HOWTO when