Serial-Programming-HOWTO.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. ============================================================================
  4. The Linux Serial Programming HOWTO, Part 1 of 2
  5. By Vernon C. Hoxie
  6. v2.0 10 September 1999
  7. This document describes how to program communications with devices
  8. over a serial port on a Linux box.
  9. ______________________________________________________________________
  10. Table of Contents
  11. 1. Copyright
  12. 2. Introduction
  13. 3. Opening
  14. 4. Commands
  15. 5. Changing Baud Rates
  16. 6. Additional Control Calls
  17. 6.1 Sending a "break".
  18. 6.2 Hardware flow control.
  19. 6.3 Flushing I/O buffers.
  20. 7. Modem control
  21. 8. Process Groups
  22. 8.1 Sessions
  23. 8.2 Process Groups
  24. 8.3 Controlling Terminal
  25. 8.3.1 Get the foreground group process id.
  26. 8.3.2 Set the foreground process group id of a terminal.
  27. 8.3.3 Get process group id.
  28. 9. Lockfiles
  29. 10. Additional Information
  30. 11. Feedback
  31. ______________________________________________________________________
  32. 1. Copyright
  33. The Linux Serial-Programming-HOWTO is copyright (C) 1997 by Vernon
  34. Hoxie. Linux HOWTO documents may be reproduced and distributed in
  35. whole or in part, in any medium physical or electronic, as long as
  36. this copyright notice is retained on all copies. Commercial
  37. redistribution is allowed and encouraged; however, the author would
  38. like to be notified of any such distributions.
  39. All translations, derivative works, or aggregate works incorporating
  40. this Linux HOWTO document must be covered under this copyright notice.
  41. That is, you may not produce a derivative work from this HOWTO and
  42. impose additional restrictions on its distribution.
  43. This version is a complete rewrite of the previous Serial-Programming-
  44. HOWTO by Peter H. Baumann, <mailto:Peter.Baumann@dlr.de>
  45. 2. Introduction
  46. This HOWTO will attempt to give hints about how to write a program
  47. which needs to access a serial port. Its principal focus will be on
  48. the Linux implementation and what the meaning of the various library
  49. functions available.
  50. Someone asked about which of several sequences of operations was
  51. right. There is no absolute right way to accomplish an outcome. The
  52. options available are too numerous. If your sequences produces the
  53. desired results, then that is the right way for you. Another
  54. programmer may select another set of options and get the same results.
  55. His method is right for him.
  56. Neither of these methods may operate properly with some other
  57. implementation of UNIX. It is strange that many of the concepts which
  58. were implemented in the SYSV version have been dumped. Because UNIX
  59. was developed by AT&T and much code has been generated on those
  60. concepts, the AT&T version should be the standard to which others
  61. should emulate.
  62. Now the standard is POSIX.
  63. It was once stated that the popularity of UNIX and C was that they
  64. were created by programmers for programmers. Not by scholars who
  65. insist on purity of style in deference to results and simplicity of
  66. use. Not by committees with people who have diverse personal or
  67. proprietary agenda. Now ANSI and POSIX have strayed from those
  68. original clear and simply concepts.
  69. 3. Opening
  70. The various serial devices are opened just as any other file.
  71. Although, the fopen(3) command may be used, the plain open(2) is
  72. preferred. This call returns the file descriptor which is required
  73. for the various commands that configure the interface.
  74. Open(2) has the format:
  75. #include <fcntl.h>
  76. int open(char *path, int flags, [int mode]);
  77. In addition to the obvious O_RDWR, O_WRONLY and O_RDONLY, two
  78. additional flags are available. These are O_NONBLOCK and O_NOCTTY.
  79. Other flags listed in the open(2) manual page are not applicable to
  80. serial devices.
  81. Normally, a serial device opens in "blocking" mode. This means that
  82. the open() will not return until the Carrier Detect line from the port
  83. is active, e.g. modem, is active. When opened with the O_NONBLOCK
  84. flag set, the open() will return immediately regardless of the status
  85. of the DCD line. The "blocking" mode also affects the read() call.
  86. The fcntl(2) command can be used to change the O_NONBLOCK flag anytime
  87. after the device has been opened.
  88. The device driver and the data passing through it are controlled
  89. according to settings in the struct termios. This structure is
  90. defined in "/usr/include/termios.h". In the Linux tree, further
  91. reference is made to "/usr/include/asm/termbits.h".
  92. In blocking mode, a read(2) will block until data is available or a
  93. signal is received. It is still subject to state of the ICANON flag.
  94. When the termios.c_lflag ICANON bit is set, input data is collected
  95. into strings until a NL, EOF or EOL character is received. You can
  96. define these in the termios.c_cc[] array. Also, ERASE and KILL
  97. characters will operate on the incoming data before it is delivered to
  98. the user.
  99. In non-canonical mode, incoming data is quanitified by use of the
  100. c_cc[VMIN and c_cc[VTIME] values in termios.c_cc[].
  101. Some programmers use the select() call to detect the completion of a
  102. read(). This is not the best way of checking for incoming data.
  103. Select() is part of the SOCKETS scheme and too complex for most
  104. applications.
  105. A full explanation of the fields of the termios structure is contained
  106. in termios(7) of the Users Manual. A version is included in Part 2 of
  107. this HOWTO document.
  108. 4. Commands
  109. Changes to the struct termios are made by retrieving the current
  110. settings, making the desired changes and transmitting the modified
  111. structure back to the kernel.
  112. The historic means of communicating with the kernel was by use of the
  113. ioctl(fd, COMMAND, arg) system call. Then the purists in the
  114. computer industry decided that this was not genetically consistent.
  115. Their argument was that the argument changed its stripes. Sometimes
  116. it was an int, sometimes it was a pointer to int and other times it
  117. was a pointer to struct termios. Then there were those times it was
  118. empty or NULL. These variations are dependent upon the COMMAND.
  119. As a alternative, the tc* series of functions were concocted.
  120. These are:
  121. int tcgetattr(int filedes, struct termios *termios_p);
  122. int tcsetattr(int filedes, int optional_actions,
  123. const struct termios *termios_p);
  124. instead of:
  125. int ioctl(int filedes, int command,
  126. struct termios *termios_p);
  127. where command is TCGETS or one of TCSETS, TCSETSW or TCSETSF.
  128. The TCSETS command is comparable to the TCSANOW optional_action for
  129. the tc* version. These direct the kernel to adopt the changes
  130. immediately. Other pairs are:
  131. command optional_action Meaning
  132. TCSETSW TCSADRAIN Change after all output has drained.
  133. TCSETSF TCSAFLUSH Change after all output has drained
  134. then discard any input characters
  135. not read.
  136. Since the return code from either the ioctl(2) or the tcsetattr(2)
  137. commands only indicate that the command was processed by the kernel.
  138. These do not indicate whether or not the changes were actually
  139. accomplished. Either of these commands should be followed by a call
  140. to:
  141. ioctl(fd, TCGETS, &new_termios);
  142. or:
  143. tcgetattr(fd, &new_termios);
  144. A user function which makes changes to the termios structure should
  145. define two struct termios variables. One of these variables should
  146. contain the desired configuration. The other should contain a copy of
  147. the kernels version. Then after the desired configuration has been
  148. sent to the kernel, another call should be made to retrieve the
  149. kernels version. Then the two compared.
  150. Here is an example of how to add RTS/CTS flow control:
  151. struct termios my_termios;
  152. struct termios new_termios;
  153. tcgetattr(fd, &my_termios);
  154. my_termios.c_flag |= CRTSCTS;
  155. tcsetattr(fd, TCSANOW, &my_termios);
  156. tcgetattr(fd, &new_termios);
  157. if (memcmp(my_termios, new_termios,
  158. sizeof(my_termios)) != 0) {
  159. /* do some error handling */
  160. }
  161. 5. Changing Baud Rates
  162. With Linux, the baud rate can be changed using a technique similar to
  163. add/delete RTS/CTS.
  164. struct termios my_termios;
  165. struct termios new_termios;
  166. tcgetattr(fd, &my_termios);
  167. my_termios.c_flag &= ~CBAUD;
  168. my_termios.c_flag |= B19200;
  169. tcsetattr(fd, TCSANOW, &my_termios);
  170. tcgetattr(fd, &new_termios);
  171. if (memcmp(my_termios, new_termios,
  172. sizeof(my_termios)) != 0) {
  173. /* do some error handling */
  174. }
  175. POSIX adds another method. They define:
  176. speed_t cfgetispeed(const struct termios *termios_p);
  177. speed_t cfgetospeed(const struct termios *termios_p);
  178. library calls to extract the current input or output speed from the
  179. struct termios pointed to with *termio_p. This is a variable defined
  180. in the calling process. In practice, the data contained in this
  181. termios, should be obtained by the tcgetattr() call or an ioctl() call
  182. using the TCGETS command.
  183. The companion library calls are:
  184. int cfsetispeed(struct termios *termios_p, speed_t speed);
  185. int cfsetospeed(struct termios *termios_p, speed_t speed);
  186. which are used to change the value of the baud rate in the locally
  187. defined *termios_p. Following either of these calls, either a call to
  188. tcsetattr() or ioctl() with one of TCSETS, TCSETSW or TCSETSF as the
  189. command to transmit the change to the kernel.
  190. The cf* commands are preferred for portability. Some weird Unices use
  191. a considerably different format of termios.
  192. Most implementations of Linux use only the input speed for both input
  193. and output. These functions are defined in the application program by
  194. reference to <termios.h>. In reality, they are in
  195. /usr/include/asm/termbits.h.
  196. 6. Additional Control Calls
  197. 6.1. Sending a "break".
  198. int ioctl(fd, TCSBRK, int arg);
  199. int tcsendbreak(fd, int arg);
  200. Send a break: Here the action differs between the conventional
  201. ioctl() call and the POSIX call. For the conventional call, an arg of
  202. '0' sets the break control line of the UART for 0.25 seconds. For the
  203. POSIX command, the break line is set for arg times 0.1 seconds.
  204. 6.2. Hardware flow control.
  205. int ioctl(fd, TCXONC, int action);
  206. int tcflow(fd, int action);
  207. The action flags are:
  208. o TCOOFF 0 suspend output
  209. o TCOON 1 restart output
  210. o TCIOFF 2 transmit STOP character to suspend input
  211. o TCION 3 transmit START character to restart input
  212. 6.3. Flushing I/O buffers.
  213. int ioctl(fd, TCFLSH, queue_selector);
  214. int tcflush(fd, queue_selector);
  215. The queue_selector flags are:
  216. o TCIFLUSH 0 flush any data not yet read from the input buffer
  217. o TCOFLUSH 1 flush any data written to the output buffer but not
  218. yet transmitted
  219. o TCIOFLUSH 2 flush both buffers
  220. 7. Modem control
  221. The hardware modem control lines can be monitored or modified by the
  222. ioctl(2) system call. A set of comparable tc* calls apparently do not
  223. exist. The form of this call is:
  224. int ioctl(fd, COMMAND, (int *)flags);
  225. The COMMANDS and their action are:
  226. o TIOCMBIS turn on control lines depending upon which bits are set
  227. in flags.
  228. o TIOCMBIC turn off control lines depending upon which bits are
  229. unset in flags.
  230. o TIOCMGET the appropriate bits are set in flags according to the
  231. current status
  232. o TIOCMSET the state of the UART is changed according to which bits
  233. are set/unset in 'flags'
  234. The bit pattern of flags refer to the following control lines:
  235. o TIOCM_LE Line enable
  236. o TIOCM_DTR Data Terminal Ready
  237. o TIOCM_RTS Request to send
  238. o TIOCM_ST Secondary transmit
  239. o TIOCM_SR Secondary receive
  240. o TIOCM_CTS Clear to send
  241. o TIOCM_CAR Carrier detect
  242. o TIOCM_RNG Ring
  243. o TIOCM_DSR Data set ready
  244. It should be noted that some of these bits are controlled by the modem
  245. and the UART cannot change them but their status can be sensed by
  246. TIOCMGET. Also, most Personal Computers do not provide hardware for
  247. secondary transmit and receive.
  248. There are also a pair of ioctl() to monitor these lines. They are
  249. undocumented as far as I have learned. The commands are TIOCMIWAIT
  250. and TCIOGICOUNT. They also differ between versions of the Linux
  251. kernel.
  252. See the lines.c file in my "serial_suite" for an example of how these
  253. can be used see <ftp://scicom.alphacd.com/pub/linux/serial_suite>
  254. 8. Process Groups
  255. 8.1. Sessions
  256. 8.2. Process Groups
  257. Any newly created process inherits the Process Group of its creator.
  258. The Process Group leader has the same PID as PGID.
  259. 8.3. Controlling Terminal
  260. There are a series of ioctl(2) and tc*(2) calls which can be used to
  261. monitor or to change the process group to which the device is
  262. attached.
  263. 8.3.1. Get the foreground group process id.
  264. If there is no foreground group, a number not representing an existing
  265. process group is returned. On error, a -1 is returned and errno is
  266. set.
  267. int ioctl(fd, TIOCGPGRP, (pid_t *)pid);
  268. int tcgetpgrp(fd, (pid_t *)pid);
  269. 8.3.2. Set the foreground process group id of a terminal.
  270. The fd must be the controlling terminal and be associated with the
  271. session of the calling process.
  272. int ioctl(fd, TIOCSPGRP, (pid_t *)pid);
  273. int tcsetpgrp(fd, (pid_t *)pid);
  274. 8.3.3. Get process group id.
  275. int ioctl(fd, TIOCGPGRP, &(pid_t)pid);
  276. int tcgetpgrp(fd, &(pid_t)pid);
  277. 9. Lockfiles
  278. Any process which accesses a serial device should first check for the
  279. existence of lock file for the desired device. If such a lock lock
  280. file exists, this means that the device may be in use by another
  281. process.
  282. Check my "libdevlocks-x.x.tgz" at
  283. <ftp://scicom.alphacdc.com/pub/linux> for an example of how these lock
  284. files should be utilized.
  285. 10. Additional Information
  286. Check out my "serial_suite.tgz" for more information about programming
  287. the serial ports at <mailto:vern@zebra.alphacdc.com>. There some
  288. examples and some blurbs about setting up modems and comments about
  289. some general considerations.
  290. 11. Feedback
  291. Please send me any corrections, questions, comments, suggestions, or
  292. additional material. I would like to improve this HOWTO! Tell me
  293. exactly what you don't understand, or what could be clearer. You can
  294. reach me at <mailto:vern@zebra.alphacdc.com> via email. Please
  295. include the version number of the Serial-Programming-HOWTO when
  296. writing.