- 论坛徽章:
- 0
|
本帖最后由 zyr-linux 于 2010-06-29 19:18 编辑
前面的话:
linux环境:虚拟机VMware Server上安装的ubuntu10.4,通过putty登录shell。
抄书:
文件描述符(file descriptor:fd)是个简单的整数,用以标明每一个被进程所打开的文件。
可以通过查看/proc/pid/fd/目录查看该进程的fd。
先从用户态开始:
编写一个helloworld,运行后通过proc可以看到进程helloworld有三个fd(0,1,2),指向3个设备文件,均为/dev/pts/0。
然后在helloworld中打开一个文件,查看会发现0、1、2没有变化,另多了一个fd(3)指向打开的文件。
继续抄书,这次是Linux Programmer's Manual:
DESCRIPTION
Under normal circumstances every Unix program has three streams opened for it when it starts up, one for input, one for output, and one for print‐\r
ing diagnostic or error messages. These are typically attached to the user's terminal (see tty(4) but might instead refer to files or other
devices, depending on what the parent process chose to set up. (See also the "Redirection" section of sh(1).)
The input stream is referred to as "standard input"; the output stream is referred to as "standard output"; and the error stream is referred to as
"standard error". These terms are abbreviated to form the symbols used to refer to these files, namely stdin, stdout, and stderr.
Each of these symbols is a stdio(3) macro of type pointer to FILE, and can be used with functions like fprintf(3) or fread(3).
Since FILEs are a buffering wrapper around Unix file descriptors, the same underlying files may also be accessed using the raw Unix file inter‐\r
face, that is, the functions like read(2) and lseek(2).
On program startup, the integer file descriptors associated with the streams stdin, stdout, and stderr are 0, 1, and 2, respectively. The pre‐\r
processor symbols STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO are defined with these values in <unistd.h>. (Applying freopen(3) to one of
these streams can change the file descriptor number associated with the stream.)
Note that mixing use of FILEs and raw file descriptors can produce unexpected results and should generally be avoided. (For the masochistic among
you: POSIX.1, section 8.2.3, describes in detail how this interaction is supposed to work.) 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 descriptors, but
all old streams have become inaccessible.
Since the symbols stdin, stdout, and stderr are specified to be macros, assigning to them is non-portable. The standard streams can be made to
refer to different files with help of the library function freopen(3), specially introduced to make it possible to reassign stdin, stdout, and
stderr. The standard streams are closed by a call to exit(3) and by normal program termination.
fd(0,1,2)就是常说的stdin、stdout、stderr;用户态程序运行时默认建立,/dev/pts/0则是运行程序时的终端。
(纯粹的内核进程则不同,后面会提到)
fd在用户态下可以通过函数dup2()进行重定向,而内核态下也有系统调用sys_dup2(),有兴趣的可以试试。 |
评分
-
查看全部评分
|