linux文件描述符0 1 2是否不适用于stdin,stdout和stderr? [英] Is it possible that linux file descriptor 0 1 2 not for stdin, stdout and stderr?
问题描述
程序启动时,默认情况下是否接受stdin,stdout和stderr的文件描述符0、1和2?由于已经使用了这些值,因此诸如open(...),socket(...)之类的API调用是否不会返回0、1和2?在任何情况下,open(...)或socket(...)都将返回0、1或2.并且0、1和2与stdin,stdout和stderr无关.
When a program begins, does it take file descriptors 0, 1 and 2 for stdin, stdout and stderr by default?. And will API calls such as open(...), socket(...) not return 0, 1 and 2 since these values are already taken?. Is there any case in which open(...) or socket(...) would return 0, 1 or 2. And 0, 1 and 2 are not related with stdin, stdout, and stderr.
推荐答案
在文件描述符级别, stdin 定义为文件描述符0 , stdout 定义为文件描述符1 ;并且 stderr 被定义为文件描述符2 .参见此.
At the file descriptor level, stdin is defined to be file descriptor 0, stdout is defined to be file descriptor 1; and stderr is defined to be file descriptor 2. See this.
即使您的程序或外壳程序发生了更改(例如,使用 dup2(2))什么是文件描述符0,它始终保持为 stdin (因为根据定义,STDIN_FILENO
为0).
Even if your program -or the shell- changes (e.g. redirect with dup2(2)) what is file descriptor 0, it always stays stdin (since by definition STDIN_FILENO
is 0).
因此, stdin 当然可以是管道,套接字或文件(而不是终端).如果它是tty,则可以使用 isatty(3)进行测试和/或使用 fstat(2)来获取状态信息
So of course stdin could be a pipe or a socket or a file (not a terminal). You could test with isatty(3) if it is a tty, and/or use fstat(2) to get status information on it.
Syscalls like open(2) or pipe(2) or socket(2) may give e.g. STDIN_FILENO
(i.e. 0) if that file descriptor is free (e.g. because it has been close(2)-d before). But when that occurs, it is still stdin by definition.
当然,在 stdio(3)中, FILE
流 stdin 有点复杂.您的程序可以 fclose(3), fdopen(3) ...
Of course, in stdio(3), the FILE
stream stdin is a bit more complex. Your program could fclose(3), freopen(3), fdopen(3) ...
当神奇地启动/sbin/init
作为内核时,内核可能会将 stdin , stdout 和 stderr 文件描述符设置到控制台.第一步.
Probably the kernel sets stdin, stdout, and stderr file descriptors to the console when magically starting /sbin/init
as the first process.
这篇关于linux文件描述符0 1 2是否不适用于stdin,stdout和stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!