簡體   English   中英

Unix:如何清除串行端口I / O緩沖區?

[英]Unix: How to clear the serial port I/O buffer?

我正在為標准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();
}

嘗試

ioctl(fd,TCFLUSH,dir)

dir等於0表示接收,1表示發送,兩者均等於2。

這是正確的方法(如下所示):

usleep(1000);
ioctl(fd, TCFLSH, 0); // flush receive
ioctl(fd, TCFLSH, 1); // flush transmit
ioctl(fd, TCFLSH, 2); // flush both

用戶可以根據需要選擇前兩行或最后一行。 請檢查是否可能需要睡眠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM