4

我有一个系统,我看到串行端口的奇怪行为是我没想到的。我以前在使用 USB 转串口适配器时偶尔会看到这种情况,但现在我在本机串口上也看到了这种情况,而且频率要高得多。

该系统设置为运行自动化测试,并且将首先执行一些任务,这些任务会导致大量数据从串行设备输出,而我没有打开端口。设备也会自行重置。仅连接 tx/rx 线。没有流量控制。

完成这些任务后,测试件打开串行端口并立即失败,因为它得到了意外的响应。当我重现这一点时,我发现如果我在终端程序中打开串行端口,我会看到几千字节的旧数据(似乎是在端口关闭时发送的)立即被清除。一旦我关闭了这个程序,我就可以按预期运行测试。

什么可能导致这种情况发生?当设备关闭时,Linux 如何处理缓冲串行端口?如果我打开一个设备,让它发送输出,然后关闭它而不读取它,这会导致同样的问题吗?

4

1 回答 1

5

Linux 终端驱动程序会缓冲输入,即使它没有打开。这可能是一个有用的功能,特别是如果速度/奇偶校验/等。设置得当。

要复制较小操作系统的行为,请在端口打开后立即从端口读取所有待处理的输入:

...
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");
}
于 2011-11-10T19:26:49.183 回答