a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > C > 正文

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

2020-01-26 16:06:49
字體:
來源:轉載
供稿:網友
先看下面一個例子
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."

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 精品成人佐山爱一区二区 | www.成人| 亚洲精品久久久 | 国产乱码一区二区三区 | 黄色av网站大全 | 亚洲精品在线播放 | 国产精品高清在线 | a在线播放| 99精品在线观看 | 日韩专区一区二区 | 日韩精品视频在线免费观看 | 国产福利在线播放麻豆 | 久久69国产一区二区蜜臀 | 91久久久www播放日本观看 | 国产精品无码久久久久 | 精品久久久久久国产 | 一区二区激情 | 国产成人+综合亚洲+天堂 | 欧美九九九| 欧美激情欧美激情在线五月 | 色噜噜狠狠狠综合曰曰曰 | 国产一区二区精品丝袜 | 日韩精品在线电影 | 亚洲精品99 | 91综合视频在线观看 | 欧美精品一区二区在线观看 | 久久再线视频 | 黄av在线播放 | 午夜精品一区二区三区在线视频 | 久久三区 | 色呦呦在线看 | 国产精品99久久免费观看 | 另类国产ts人妖高潮系列视频 | 精品成人在线 | 久久免费在线观看 | 亚洲精品久久久 | 一级黄色片子免费看 | 欧美福利二区 | 奇米影视奇米色777欧美 | 久久电影国产 | 国产成人99久久亚洲综合精品 |