-
定义
文件描述符是用来访问文件的一个小整数,是操作系统访问特定文件的标志。
-
用法
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
char buf[1024];
ssize_t s=read(0,buf,sizeof(buf));
if(s>0)
{
buf[s]=0;
write(1,buf,strlen(buf));
write(2,buf,strlen(buf));
}
return 0;
}
-
默认的文件描述符
Linux进程默认情况下会有3个缺省打开的文件描述符,分别是标准输入(stdin)0,标准输出(stdout)1,标准错误(error)2;0,1,2对应的物理设备一般是:键盘,显示器,显示器。所以输入输出还可以采用如下方式:
-
作用
每当打开一个新的文件,在task_struct中从上向下找到一个最小的,未被使用的文件或数组元素,然后把新的文件地址填充到这个元素当中,最终返回对应数组的下标。当以后想访问这个文件时,只用把数组的下标给进程就行,我们根据下标找到该文件的PCB,file_struct及file*数组,再根据下标确认访问的是哪个文件。
-
本质
本质上,文件描述符就是file_struct中数组的下标,只要拿着文件描述符,就可以找到对应的文件。
-
分配规则
用一段代码来说明:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd=open("myfile",O_RDONLY);
if(fd<0)
{
perror("open");
return 1;
}
printf("fd:%d\n",fd);
close(fd);
return 0;
}
输出结果为:
这里之所以是3,是因为Linux进程默认情况下会有3个缺省打开的文件描述符,分别是标准输入(stdin)0,标准输出(stdout)1,标准错误(error)2
我们再关闭0:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
close(0);
int fd=open("fd.c",O_RDONLY);
if(fd<0)
{
perror("open");
return 1;
}
printf("fd:%d\n",fd);
close(fd);
return 0;
}
输出结果为:
再关闭2:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
close(2);
int fd=open("fd.c",O_RDONLY);
if(fd<0)
{
perror("open");
return 1;
}
printf("fd:%d\n",fd);
close(fd);
return 0;
}
输出结果为:
通过上面的实践,我们不难发现,文件描述符的分配规则是:从最小的,未被使用的小整数开始分配。