作用
判断文件描述符是否为终端(输出设备句柄)
相关联的函数 ttyname
作用
返回终端名(路径)
使用
ttyname(int)
相关联函数 fileno
作用
把文件流指针转换成文件描述符
使用
fileno(FILE *)
返回值
!= null 终端名(路径)
== null 文件描述符不是终端
头文件
#include <sdtio.h>
返回值
1 文件描述符为终端
0 文件描述符不是终端
示例
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
void fd_test(int fd){
if(isatty(fd)){
printf("fd is a tty tty path = %s\n",ttyname(fd));
}else{
printf("fd is not a tty\n");
}
}
void test (char *path)
{
int fd = open(path,O_RDONLY);
if(fd < 0){
printf("open fail\n");
return;
}
fd_test(fd);
close(fd);
}
void test1 (char * path){
FILE *file = fopen(path,"r");
if(!file){
printf("fopen fail");
return;
}
fd_test(fileno(file));
fclose(file);
}
int main ( int argc, char *argv[] )
{
test("/dev/tty");
test("./test");
fd_test(fileno(stdin));
fd_test(fileno(stdout));
fd_test(fileno(stderr));
test1("/dev/tty");
test1("./test");
return 0;
}
结果
3 is a tty tty path = /dev/tty
fd is not a tty
0 is a tty tty path = /dev/pts/0
1 is a tty tty path = /dev/pts/0
2 is a tty tty path = /dev/pts/0
3 is a tty tty path = /dev/tty
fd is not a tty