Linux打开设备时串口缓冲区不为空 [英] Linux serial port buffer not empty when opening device
问题描述
我有一个系统,我发现串行端口的异常行为是我没想到的.我以前偶尔在使用 USB 转串口适配器时看到过这种情况,但现在我在本机串口上也看到过这种情况,而且频率要高得多.
I have a system where I am seeing strange behavior with the serial ports that I don't expect. I've previously seen this on occasion with usb-to-serial adapters, but now I'm seeing it on native serial ports as well, with much greater frequency.
系统设置为运行自动化测试,并且在我没有打开端口的情况下,将首先执行一些导致从串行设备输出大量数据的任务.设备也会自行重置.仅连接 tx/rx 线.没有流量控制.
The system is set up to run automated tests and will first perform some tasks that cause a large amount of data to be outputted from the serial device while I do not have the ports open. The device will also reset itself. Only the tx/rx lines are connected. There is no flow control.
这些任务完成后,测试件打开串口并立即失败,因为它得到了意外的响应.当我重现这一点时,我发现如果我在终端程序中打开串行端口,我会看到几千字节的旧数据(似乎是在端口关闭时发送的)立即被清除.关闭此程序后,我就可以按预期运行测试了.
After these tasks complete, the testware opens the serial ports and immediately fails because it gets unexpected responses. When I reproduce this, I found that if I open the serial port in a terminal program, I see several kilobytes of old data (that appears to have been sent when the port was closed) immediately flushed out. Once I close this program, I can then run the tests as expected.
什么可能导致这种情况发生?当设备关闭时,Linux 如何处理缓冲串行端口?如果我打开一个设备,让它发送输出,然后关闭它而不读取它,这会导致同样的问题吗?
What could cause this to happen? How does Linux handle buffering the serial port when the device is closed? If I opened a device, made it send output, and then closed it without reading from it, would this cause the same problem?
推荐答案
即使没有打开Linux终端驱动程序也会缓冲输入.这可能是一个有用的功能,特别是如果速度/奇偶校验/等.设置得当.
The Linux terminal driver buffers input even if it is not opened. This can be a useful feature, especially if the speed/parity/etc. are set appropriately.
要复制较小操作系统的行为,请在端口打开后立即从端口读取所有待处理的输入:
To replicate the behavior of lesser operating systems, read all pending input from the port as soon as it is open:
...
int fd = open ("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
exit (1);
set_blocking (fd, 0); // disable reads blocked when no input ready
char buf [10000];
int n;
do {
n = read (fd, buf, sizeof buf);
} while (n > 0);
set_blocking (fd, 1); // enable read blocking (if desired)
... // now there is no pending input
void set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
error ("error %d getting term settings set_blocking", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = should_block ? 5 : 0; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
error ("error setting term %sblocking", should_block ? "" : "no");
}
这篇关于Linux打开设备时串口缓冲区不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!