国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C > 正文

解析c中stdout與stderr容易忽視的一些細(xì)節(jié)

2020-01-26 16:06:49
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
先看下面一個(gè)例子
a.c :
復(fù)制代碼 代碼如下:

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
我們看到, 重定向到一個(gè)文件后, bad 到了 normal 的前面.
原因如下:
復(fù)制代碼 代碼如下:

"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. "

因此, 可以使用如下的代碼:
復(fù)制代碼 代碼如下:

int main(int argc, char *argv[])
{
 fprintf(stdout, " normal/n");
 fflush(stdout);
 fprintf(stderr, " bad/n");
 return 0;
}

這樣重定向到一個(gè)文件后就正常了. 但是這種方法只適用于少量的輸出, 全局的設(shè)置方法還需要用 setbuf() 或 setvbuf(), 或者采用下面的系統(tǒng)調(diào)用:
復(fù)制代碼 代碼如下:

int main(int argc, char *argv[])
{
 write(1, "normal/n", strlen("normal/n"));
 write(2, "bad/n", strlen("bad/n"));
 return 0;
}

但是盡量不要同時(shí)使用 文件流 和 文件描述符,
復(fù)制代碼 代碼如下:

"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."

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 麻阳| 清丰县| 伊吾县| 香港| 汕头市| 固阳县| 宜黄县| 长沙县| 玉山县| 陇川县| 澜沧| 平塘县| 南乐县| 南昌市| 永新县| 上饶市| 蓝山县| 黎平县| 肥城市| 德格县| 马公市| 庄河市| 清流县| 武功县| 安新县| 科技| 六安市| 朝阳市| 佳木斯市| 葫芦岛市| 永年县| 伽师县| 彰武县| 色达县| 宣武区| 浦东新区| 临沂市| 霍城县| 南城县| 深泽县| 衡阳县|