微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux-将块缓冲的数据写入没有fflush(stdout)的文件

据我对缓冲区的了解:缓冲区是临时存储的数据.

例如:假设您要实现一种算法来确定某物是语音还是噪声.您如何使用恒定的声音数据流来做到这一点?这将是非常困难的.因此,通过将其存储到阵列中,您可以对该数据进行分析.

该数据数组称为缓冲区.

现在,我有一个Linux命令,其中的输出是连续的:

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2)}' < /dev/ttyUSB0

如果我要将此命令的输出写入文件,将无法写入,因为输出可能是块缓冲的,当我终止上述命令的输出时,只会生成一个空的文本文件( CTRL C).

这就是块缓冲的意思.

The three types of buffering available are unbuffered, block
buffered, and line buffered. When an output stream is unbuffered,
information appears on the destination file or terminal as soon as
written; when it is block buffered many characters are saved up and
written as a block; when it is line buffered characters are saved
up until a newline is output or input is read from any stream
attached to a terminal device (typically stdin). The function
fflush(3) may be used to force the block out early. (See
fclose(3).) normally all files are block buffered. When the first
I/O operation occurs on a file, malloc(3) is called, and a buffer
is obtained. If a stream refers to a terminal (as stdout normally
does) it is line buffered. The standard error stream stderr is
always unbuffered by default.

现在,执行此命令,

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2)}' < /dev/ttyUSB0 > outputfile.txt

生成一个文件,因为终止进程时缓冲区块可能尚未完成,并且由于我不知道块缓冲区的大小,因此无法等待该块完成.

为了将该命令的输出写入文件,我必须在awk中使用fflush(),它将成功将输出写入文本文件,而我已经成功完成了.

它去了:

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/GGA/ {print  "Latitude:",$3,$4,"Longitude:",$5,$6,"Altitude:",$10,$11,"Time:",substr($2+50000,1,2),".",substr($2,3,2),".",substr($2,5,2); fflush(stdout) }' < /dev/ttyUSB0 | head -n 2 > GPS_data.txt

但是我的问题是:

有什么方法可以声明缓冲区块的大小,以便我知道何时生成缓冲区块,从而不需要使用fflush()吗?

要么

是否有将缓冲区类型从块缓冲更改为非缓冲或行缓冲的方法

解决方法:

您可以使用stdbuf运行修改了缓冲区大小的命令.

例如,stdbuf -o 100 awk …将使用100字节标准输出缓冲区运行awk.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐