- 論壇徽章:
- 0
|
本帖最后由 zyr-linux 于 2010-06-29 19:18 編輯
前面的話:
linux環(huán)境:虛擬機VMware Server上安裝的ubuntu10.4,通過putty登錄shell。
抄書:
文件描述符(file descriptor:fd)是個簡單的整數(shù),用以標明每一個被進程所打開的文件。
可以通過查看/proc/pid/fd/目錄查看該進程的fd。
先從用戶態(tài)開始:
編寫一個helloworld,運行后通過proc可以看到進程helloworld有三個fd(0,1,2),指向3個設(shè)備文件,均為/dev/pts/0。
然后在helloworld中打開一個文件,查看會發(fā)現(xiàn)0、1、2沒有變化,另多了一個fd(3)指向打開的文件。
繼續(xù)抄書,這次是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;用戶態(tài)程序運行時默認建立,/dev/pts/0則是運行程序時的終端。
(純粹的內(nèi)核進程則不同,后面會提到)
fd在用戶態(tài)下可以通過函數(shù)dup2()進行重定向,而內(nèi)核態(tài)下也有系統(tǒng)調(diào)用sys_dup2(),有興趣的可以試試。 |
評分
-
查看全部評分
|