title: Unix: How to clear the serial port I/O buffer?
body: <p>I am working on a "high level" C++ interface for the standard PC serial port. When I open the port, I would like to clear the input and output buffers in order not to receive or send data from previous usage of the port. To do that, I use the tcflush function. However, it does not work. How can that be? My "port opening" code can be seen below. Yes I use C++ exceptions but none are getting thrown. That indicates that tcflush returns 0 but it does not clear the buffer.</p>
  
  <p>The only way I can clear the input buffer is to read bytes from it until there is none left. This usually takes a couple of seconds and I do not think of it as a solution.</p>
  
  <p>Thanks in advance :-)</p>
  
  <pre><code>fd = ::open(port.c_str(), O_RDWR | O_NOCTTY);
  
  if (fd &lt; 0)
  {
      throw OpenPortException(port);
      return;
  }
  
  // Get options
  tcgetattr(fd, &amp;options);
  
  // Set default baud rate 9600, 1 stop bit, 8 bit data length, no parity
  options.c_cflag &amp;= ~PARENB;
  options.c_cflag &amp;= ~CSTOPB;
  options.c_cflag &amp;= ~CSIZE;
  options.c_cflag |= CS8;
  
  // Default timeout (1000 ms)
  options.c_cc[VMIN] = 0;
  options.c_cc[VTIME] = 10;
  
  // Additional options
  options.c_cflag |= (CLOCAL | CREAD);
  
  this-&gt;port = port;
  
  // Apply the settings now
  if (tcsetattr(fd, TCSANOW, &amp;options) != 0)
  {
      throw PortSettingsException();
  }
  
  // Flush the port
  if (tcflush(fd, TCIOFLUSH) != 0)
  {
      throw IOException();
  }
  </code></pre>