flush linux OS serial buffer

4.9k Views Asked by At

I have a serial program connecting to two devices via two different ports. Whenever I read, of course I have a local buffer with allocated statically with size of packet I am willing to read from serial. My boss, however, noted that storing packets to this local buffer will not be safe, rather he advised to check if I can flush linux OS buffer every time I read from serial. what is your opinion? and how can I do that programatically in ubuntu ?

I think this problem gets solved, if I add TCSAFLUSH to the tcsetattr function. this makes it flush the buffer after all data has been written to serial. this happens just before the next read. hopefully if I usleep() for some time ;) what if your opinion?

1

There are 1 best solutions below

0
Majenko On

The function you are looking for is tcdrain(fd) or the tcsetattr() option TCSADRAIN.

TCSAFLUSH (and tcflush()) empty the buffer by discarding the data - tcdrain() waits (blocking) until all data has been sent from the buffer:

Line control

...

tcdrain() waits until all output written to the object referred to by fd has been transmitted.

-- man termios

I use the function just before resetting the port options to what they were before I changed them and close the port:

void SerialPort::close() {
    if (_fd > -1) {
        tcdrain(_fd);
        ioctl(_fd, TCSETS2, &_savedOptions);
        ::close(_fd);
    }
    _fd = -1;
}