gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:16:44 24 4
gpt4 key购买 nike

我试图用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com