标签:
当Linux创建一个进程时,会自动创建3个文件描述符0,1,2,分别对应标准输入,标准输出,错误输出。C库中与文件描述符对应的是文件指针。查看C库头文件stdio.h中的源码
typedef struct _IO_FILE FILE; //文件流类型
- extern struct _IO_FILE *stdin; /* 标准输入流 */
extern struct _IO_FILE *stdout; /* 标准输出流 */
extern struct _IO_FILE *stderr; /* 错误流 */
#ifdef __STDC__
/* C89/C99 say they‘re macros. Make them happy. */
#define stdin stdin
#define stdout stdout
#define stderr stderr
#endif
_IO_FILE *stdin = (FILE *) &_IO_2_1_stdin_;
_IO_FILE *stdout = (FILE *) &_IO_2_1_stdout_;
_IO_FILE *stderr = (FILE *) &_IO_2_1_stderr_;
DEF_STDFILE(_IO_2_1_stdin_, 0, 0, _IO_NO_WRITES);
DEF_STDFILE(_IO_2_1_stdout_, 1, &_IO_2_1_stdin_, _IO_NO_READS);
DEF_STDFILE(_IO_2_1_stderr_, 2, &_IO_2_1_stdout_, _IO_NO_READS+_IO_UNBUFFERED);
_IO_FILE *
_IO_new_file_fopen (fp, filename, mode, is32not64)
_IO_FILE *fp;
const char *filename;
const char *mode;
int is32not64;
{
int oflags = 0, omode;
int read_write;
int oprot = 0666;
int i;
_IO_FILE *result;
#ifdef _LIBC
const char *cs;
const char *last_recognized;
#endif
if (_IO_file_is_open (fp))
return 0;
switch (*mode)
{
case ‘r‘:
omode = O_RDONLY;
read_write = _IO_NO_WRITES;
break;
case ‘w‘:
omode = O_WRONLY;
oflags = O_CREAT|O_TRUNC;
read_write = _IO_NO_READS;
break;
case ‘a‘:
omode = O_WRONLY;
oflags = O_CREAT|O_APPEND;
read_write = _IO_NO_READS|_IO_IS_APPENDING;
break;
default:
__set_errno (EINVAL);
return NULL;
}
#ifdef _LIBC
last_recognized = mode;
#endif
for (i = 1; i < 7; ++i)
{
switch (*++mode)
{
case ‘\0‘:
break;
case ‘+‘:
omode = O_RDWR;
read_write &= _IO_IS_APPENDING;
#ifdef _LIBC
last_recognized = mode;
#endif
continue;
case ‘x‘:
oflags |= O_EXCL;
#ifdef _LIBC
last_recognized = mode;
#endif
continue;
case ‘b‘:
#ifdef _LIBC
last_recognized = mode;
#endif
continue;
case ‘m‘:
fp->_flags2 |= _IO_FLAGS2_MMAP;
continue;
case ‘c‘:
fp->_flags2 |= _IO_FLAGS2_NOTCANCEL;
continue;
case ‘e‘:
#ifdef O_CLOEXEC
oflags |= O_CLOEXEC;
#endif
fp->_flags2 |= _IO_FLAGS2_CLOEXEC;
continue;
default:
/* Ignore. */
continue;
}
break;
}
result = _IO_file_open (fp, filename, omode|oflags, oprot, read_write,
is32not64);
#include <stdio.h>
FILE *fdopen(int fd, const char *mode);
int fileno(FILE *stream);
int fileno (_IO_FILE* fp)
{
CHECK_FILE (fp, EOF);
if (!(fp->_flags & _IO_IS_FILEBUF) || _IO_fileno (fp) < 0)
{
__set_errno (EBADF);
return -1;
}
return _IO_fileno (fp);
}
#define _IO_fileno(FP) ((FP)->_fileno)
标签:
原文地址:http://www.cnblogs.com/zengyiwen/p/5755187.html