解析c中stdout與stderr容易忽視的一些細節

來源:互聯網
上載者:User

先看下面一個例子
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(), 或者採用下面的系統調用: 複製代碼 代碼如下: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."

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.