isatty()在C中的作用是什么?
嗨,有人能告诉我c中isatty()的参数是什么吗。 我有下面的代码,但我不明白第一个输出三个数字是1,剩下的都是0isatty()在C中的作用是什么?,c,linux,C,Linux,嗨,有人能告诉我c中isatty()的参数是什么吗。 我有下面的代码,但我不明白第一个输出三个数字是1,剩下的都是0 #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(){ for(int i=0;i<100;i++){ int t=isatty(i); printf("%d",t);
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
for(int i=0;i<100;i++){
int t=isatty(i);
printf("%d",t);
}
return 0;
}
#包括
#包括
#包括
int main(){
对于(int i=0;i,它告诉您文件描述符是否连接到终端
您可以在此处阅读更多信息:检查:
isatty-测试文件描述符是否引用终端
快速查看您的手册页将发现:
int isatty(int fildes);
DESCRIPTION
The isatty() function tests whether fildes, an open file
descriptor, is associated with a terminal device.
进一步调查会发现,文件描述符0、1和2(也称为STDIN_FILENO、STDOUT_FILENO和STDERR_FILENO)按惯例设置为在程序从终端运行时指向终端。isatty()
是一个函数,如果fd-(文件描述符)为指终端
它属于#包括
#包括
“但isatty()所取参数的含义是什么?”
该参数是标准I/O库的文件描述符表的索引。索引0、1和2是为stdin
、stdout
和stderr
保留的。所有其他索引都指您可以/已经打开的文件描述符。Isatty()用于检查fd(文件描述符)属于终端或命令行提示。
当它属于终端时,此函数为您提供二进制值1
它用于包含
头文件中的unistd.h关键字
如果fd是一个指向终端的开放文件描述符,isatty()将为您提供1;否则返回0如果您仍然感兴趣,我在几年前遇到了MSDOS实现
/*
** Return "true" if fd is a device, else "false"
*/
isatty(fd) int fd; {
fd; /* fetch handle */
#asm
push bx ; save 2nd reg
mov bx,ax ; place handle
mov ax,4400h ; ioctl get info function
int 21h ; call BDOS
pop bx ; restore 2nd reg
mov ax,dx ; fetch info bits
and ax,80h ; isdev bit
#endasm
}
把它读成是tty?
。这可能会有帮助。也就是说,Read man isatty--“isatty()函数测试fd是否是一个指向终端的打开文件描述符。”这是一个POSIX函数,不是来自C标准库。谢谢!但isatty()所取参数的含义是什么?不,它测试它是否是一个指向终端的开放文件描述符。谢谢!你能告诉我如何找到每个int指向的文件描述符吗?没有标准的方法。@Hao9000如果你想要文件描述符指向的文件名,在Linux上你可以使用readlink
,看到这个答案没有给出much比手册页中可以找到的信息更多。但是,我不太确定这在不同的情况下会如何表现。例如,假设我从终端(tty)运行一个程序,但将其标准输出重定向到一个文件。如果程序运行isatty(STDOUT\u FILENO),会得到什么
?我们可以使用此函数来测试程序是否在终端中运行吗?如果是,如何运行?换句话说,一些关于何时使用此函数的实际示例会很好。手册页可能是最好的答案。如果您的输出被重定向到文件,则STDOUT_FILENO指的是一个文件。它不是终端。它以什么方式不支持回答这个问题(只要它不比这里的其他答案严重)
/*
** Return "true" if fd is a device, else "false"
*/
isatty(fd) int fd; {
fd; /* fetch handle */
#asm
push bx ; save 2nd reg
mov bx,ax ; place handle
mov ax,4400h ; ioctl get info function
int 21h ; call BDOS
pop bx ; restore 2nd reg
mov ax,dx ; fetch info bits
and ax,80h ; isdev bit
#endasm
}