由於輸出很少,程序又不是正常結束(通過ctrl+c結束), 導致標準輸出重定向到文件的內容爲空
原因在於標準輸出的緩衝模式
標準輸出(stdout)的緩衝原理
緩衝類型分爲三種:
- 無緩衝
- 行緩衝
- 全緩衝
stderr默認緩衝就是無緩衝。而stdout的緩衝類型與輸出介質有關:
屏幕或者終端:行緩衝
重定向文件、管道:全緩衝
爲什麼和輸出介質有關,這很可能是shell重定向時候dup2的設置
解決方法一
顯示調用fflush
這種方法的缺點有兩個:效率、使用不方便。 (因爲你可能需要重新設置信號處理函數來處理ctrl+c, 或者kill -9 這種情況根本無法解決)
解決方法二
c函數setvbuf
https://www.runoob.com/cprogramming/c-function-setvbuf.html
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
setvbuf(stdout, NULL, _IOLBF, 0); //設置stdout的緩衝類型爲行緩衝,
明確指定緩衝類型之後重定向就會使用該緩衝類型
Except for unbuffered files, the buf argument should point to a buffer at least size bytes long; this buffer will be used instead of the cur rent buffer. If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation. The setvbuf() function may be used only after opening a stream and before any other operations have been performed on it
注意這裏setvbuf如果buf參數爲NULL,則使用默認緩衝
另外行緩衝的語義是當遇到回車或者buffer滿了之後真正輸出到介質
全緩衝的語義就是buffer滿了輸出到介質
無緩衝就是直接輸出到介質