linux - 在不等待换行的情况下在 Linux 上记录 RS232

标签 linux logging serial-port

我试图用 cat 将数据从 RS232 记录到一个文件中:

cat /dev/ttyS0 > rs232.log

结果是我的文件中除了最后一行之外的所有内容。

通过打印到标准输出,我发现 cat 仅在它获得换行符('\n')时才写入输出。我发现了相同的:

dd bs=1 if=/dev/ttyS0 of=rs232.log

看完How can I print text immediately without waiting for a newline in Perl?我开始思考,这是否可能是 Linux 内核或 coreutils 包的缓冲问题。

根据TJD的评论,我用C写了自己的程序,但仍然有同样的问题:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* args[])
{
    char buffer;
    FILE* serial;
    serial = fopen(args[1],"r");
    while(1)
    {
        buffer = fgetc(serial);
        printf("%c",buffer);
    }
}

根据我自己的 C 代码的结果,这似乎是一个与 Linux 内核相关的问题。

最佳答案

您正在打开 TTY。当该 TTY 处于熟化(又名规范)模式时,它执行行处理(例如,退格键从缓冲区中删除前一个字符)。您需要将 TTY 置于原始模式,以便在它到达时获取每个字节,而不是等待行尾。

来自 the man page :

Canonical and noncanonical mode

The setting of the ICANON canon flag in c_lflag determines whether the terminal is operating in canonical mode (ICANON set) or noncanonical mode (ICANON unset). By default, ICANON set.

In canonical mode:

  • Input is made available line by line. An input line is available when one of the line delimiters is typed (NL, EOL, EOL2; or EOF at the start of line). Except in the case of EOF, the line delimiter is included in the buffer returned by read(2).

  • Line editing is enabled (ERASE, KILL; and if the IEXTEN flag is set: WERASE, REPRINT, LNEXT). A read(2) returns at most one line of input; if the read(2) requested fewer bytes than are available in the current line of input, then only as many bytes as requested are read, and the remaining characters will be available for a future read(2).

In noncanonical mode input is available immediately (without the user having to type a line-delimiter character), and line editing is disabled.

最简单的方法就是调用 cfmakeraw

关于linux - 在不等待换行的情况下在 Linux 上记录 RS232,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709326/

相关文章:

linux - SVN - 通过 VIM 提交 - 恢复失败的提交消息

linux - 在生产 Linux 服务器上运行更新

javascript - 如何制作 log.csv 文件以在一行中记录 400 个 .jpeg 名称 (Photoshop/JavaScript)

c# - ASP.NET Core 登录 2 个不同的文件

delphi - 读取之前获取串行端口上等待的字节数

linux - docker 网络命名空间在 ip netns 列表中不可见

python - 为什么Python日志记录模块的源代码在try中引发异常?

android - 通过 USB 使用 Android 进行数据收集

hardware - 如何从网页中的串行端口读取

Linux bash pidof 命令不起作用