stdin, stdout, stderr与STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO

来源:互联网 发布:淘宝乐伊尚女装 编辑:程序博客网 时间:2024/05/14 17:47

stdin,stdout,stderr这三个都是FILE *类型,分别为:标准输入文件,标准输出文件,标准错误文件。


而STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO是文件描述符,定义在<unistd.h>中,类型为int。

/* Standard file descriptors.  */#define STDIN_FILENO    0   /* Standard input.  */#define STDOUT_FILENO   1   /* Standard output.  */#define STDERR_FILENO   2   /* Standard error output.  */

下面是一个例子:

#include <stdio.h>#include <unistd.h>           int main(){    printf("STDIN_FILENO[%d]\n", STDIN_FILENO);    printf("STDOUT_FILENO[%d]\n", STDOUT_FILENO);    printf("STDERR_FILENO[%d]\n", STDERR_FILENO);    printf("stdin[%d]\n", stdin);      printf("stdout[%d]\n", stdout);    printf("stderr[%d]\n", stderr);    return 0;}

输出为:

STDIN_FILENO[0]STDOUT_FILENO[1]STDERR_FILENO[2]stdin[1970849440]stdout[1970849664]stderr[1970849888]

可以清楚的看到他们的文件类型的区别。


另外,在stdin的man手册中,有这么一句话:

On program startup, the integer file descriptors associated with the streams stdin, stdout, and stderr are 0, 1, and 2, respectively.

A general rule is that file descriptors are handled in the kernel, while stdio is just a library.This means for example, that after an exec(3), the child inherits all open file descrip-       tors, but all old streams have become inaccessible.


一个通常的法则是,文件描述符是由内核处理,而标准输入输出只是一个库。stderr是非缓冲的,当指向一个终端的时候,stdout是行缓冲的。当调用fflush或exec或打印换行符后,才会显示。

原创粉丝点击