解析c中stdout與stderr容易忽視的一些細節(jié)
來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊: 次
先看下面一個例子
a.c :
復制代碼 代碼如下:
int main(int argc, char *argv[])
{
fprintf(stdout, "normal\n");
fprintf(stderr, "bad\n");
return 0;
}
$ ./a
normal
bad
$ ./a > tmp 2>&1
$ cat tmp
bad
tmp
我們看到, 重定向到一個文件后, bad 到了 normal 的前面.
原因如下:
復制代碼 代碼如下:
"The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a
terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline
is printed. This can produce unexpected results, especially with debugging output. The
buffering mode of the standard streams (or any other stream) can be changed using the
setbuf(3) or setvbuf(3) call. "
因此, 可以使用如下的代碼:
復制代碼 代碼如下:
int main(int argc, char *argv[])
{
fprintf(stdout, " normal\n");
fflush(stdout);
fprintf(stderr, " bad\n");
return 0;
}
這樣重定向到一個文件后就正常了. 但是這種方法只適用于少量的輸出, 全局的設置方法還需要用 setbuf() 或 setvbuf(), 或者采用下面的系統(tǒng)調用:
復制代碼 代碼如下:
int main(int argc, char *argv[])
{
write(1, "normal\n", strlen("normal\n"));
write(2, "bad\n", strlen("bad\n"));
return 0;
}
但是盡量不要同時使用 文件流 和 文件描述符,
復制代碼 代碼如下:
"Note that mixing use of FILEs and raw file descriptors can produce unexpected results and
should generally be avoided. A general rule is that file
descriptors are handled in the kernel, while stdio is just a library. This means for exam-
ple, that after an exec(), the child inherits all open file descriptors, but all old
streams have become inaccessible."
欄 目:C語言
下一篇:解析如何在C語言中調用shell命令的實現(xiàn)方法
本文標題:解析c中stdout與stderr容易忽視的一些細節(jié)
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/4462.html
您可能感興趣的文章
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對數(shù)怎么表達
- 04-02c語言沒有round函數(shù) round c語言
- 04-02C語言中怎么打出三角函數(shù) c語言中怎么打出三角函數(shù)的值
- 01-10數(shù)據(jù)結構課程設計- 解析最少換車次數(shù)的問題詳解
- 01-10深入理解C++中常見的關鍵字含義
- 01-10深入Main函數(shù)中的參數(shù)argc,argv的使用詳解
- 01-10APUE筆記之:進程環(huán)境詳解
- 01-10深入解析最長公共子串
- 01-10c++中inline的用法分析


閱讀排行
本欄相關
- 04-02c語言函數(shù)調用后清空內存 c語言調用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調用函數(shù)求fibo C語言調用函數(shù)求
隨機閱讀
- 01-10C#中split用法實例總結
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 04-02jquery與jsp,用jquery
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10delphi制作wav文件的方法