10

I've read the GNU manual for tcsetattr() and it states that the function has three arguments: a file descriptor, a value that explains how to deal with queued I/O and a pointer to a struct termios. However, I don't understand what the differences between the different values (TCSANOW, TCSADRAIN, TCSAFLUSH, TCSASOFT) are.

Could someone please explain?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Areg Sarvazyan
  • 199
  • 2
  • 13

1 Answers1

11

The POSIX specification for tcsetattr() says:

  • If optional_actions is TCSANOW, the change shall occur immediately.

  • If optional_actions is TCSADRAIN, the change shall occur after all output written to fildes is transmitted. This function should be used when changing parameters that affect output.

  • If optional_actions is TCSAFLUSH, the change shall occur after all output written to fildes is transmitted, and all input so far received but not read shall be discarded before the change is made.

The point of these is that if you're writing to a serial terminal, it may take time for data written to be flushed. The different values ensure that change occurs when you want it to.

The TCSASOFT one is custom to BSD and Linux. You can see from the manual page you quote:

  • TCSANOW — Make the change immediately.

  • TCSADRAIN — Make the change after waiting until all queued output has been written. You should usually use this option when changing parameters that affect output.

  • TCSAFLUSH — This is like TCSADRAIN, but also discards any queued input.

  • TCSASOFT — This is a flag bit that you can add to any of the above alternatives. Its meaning is to inhibit alteration of the state of the terminal hardware. It is a BSD extension; it is only supported on BSD systems and GNU/Hurd systems.

    Using TCSASOFT is exactly the same as setting the CIGNORE bit in the c_cflag member of the structure termios-p points to. See Control Modes, for a description of CIGNORE.

CIGNORE is not a POSIX attribute.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • So when should each (of the POSIX ones) be used? – user129393192 Jul 19 '23 at 00:33
  • You use the flags you need to handle your device correctly. If you use `TCSANOW`, the attributes will change, which may alter the way the data pending to the device is treated (for example, if you change the parity handling). If you use `TCSADRAIN`, then the currently queued output will complete using the current settings, and then the characteristics will change. This might be a good idea if you diddle with the parity, for example. If you're reading as well as writing, using `TCSAFLUSH` will clear all pending input as well as waiting for the output to complete. – Jonathan Leffler Jul 19 '23 at 14:56