Unix:如何清除串口I/O缓冲区?

pvh*_*987 1 c c++ unix serial-port

我正在为标准 PC 串行端口开发“高级”C++ 接口。当我打开端口时,我想清除输入和输出缓冲区,以便不接收或发送以前使用该端口的数据。为此,我使用 tcflush 函数。然而,它不起作用。怎么可能?我的“端口开放”代码如下所示。是的,我使用 C++ 异常,但没有抛出任何异常。这表明 tcflush 返回 0 但它不会清除缓冲区。

我清除输入缓冲区的唯一方法是从中读取字节,直到没有剩余字节为止。这通常需要几秒钟,我不认为这是一个解决方案。

提前致谢 :-)

fd = ::open(port.c_str(), O_RDWR | O_NOCTTY);

if (fd < 0)
{
    throw OpenPortException(port);
    return;
}

// Get options
tcgetattr(fd, &options);

// Set default baud rate 9600, 1 stop bit, 8 bit data length, no parity
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~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->port = port;

// Apply the settings now
if (tcsetattr(fd, TCSANOW, &options) != 0)
{
    throw PortSettingsException();
}

// Flush the port
if (tcflush(fd, TCIOFLUSH) != 0)
{
    throw IOException();
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*mmy 5

这是正确的方法(如下):

usleep(1000);
ioctl(fd, TCFLSH, 0); // flush receive
ioctl(fd, TCFLSH, 1); // flush transmit
ioctl(fd, TCFLSH, 2); // flush both
Run Code Online (Sandbox Code Playgroud)

用户可以根据需要选择前两行或单独选择最后一行。请检查是否需要睡眠。