国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表

圖片精選

主站蜘蛛池模板: 石家庄市| 桦甸市| 峡江县| 三河市| 黎城县| 九龙县| 呼玛县| 彭州市| 仁布县| 大丰市| 临邑县| 高平市| 广河县| 旬邑县| 怀来县| 昔阳县| 崇文区| 辽阳市| 房山区| 东乌| 榆树市| 车险| 贵州省| 蒙自县| 旬阳县| 丰县| 綦江县| 师宗县| 瑞金市| 龙江县| 贵德县| 齐河县| 株洲县| 宜兰县| 宜都市| 称多县| 石阡县| 邵武市| 准格尔旗| 全州县| 调兵山市|