天天看點

linux緩存寫入檔案,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.

标簽:bash,awk,buffer,block,linux

來源: https://codeday.me/bug/20191122/2058276.html