通过对
open
函数的学习,我们知道了文件描述符就是一个小整数
Linux
进程默认情况下会有
3
个缺省打开的文件描述符,分别是标准输入
0
, 标准输出
1
,
标准错误
2.
0,1,2
对应的物理设备一般是:键盘,显示器,显示器
所以输入输出还可以采用如下方式:
#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;
}
而现在知道,文件描述符就是从
0开始的小整数。当我们打开文件时,操作系统在内存中要创
建相应的数据结构来描述目标文件。于是就有了
fifile
结构体。表示一个已经打开的文件对象。
而进程执行
open系统调用,所以必须让进程和文件关联起来。每个进程都有一个指针
*fifiles,
指向一张表
fifiles_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;
}
输出发现是
fd: 3
关闭
0
或者
2
,再看
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
close(0);
//close(2);
int fd = open("myfile", O_RDONLY);
if(fd < 0){
perror("open");
return 1;
}
printf("fd: %d\n", fd);
close(fd);
return 0;
}
发现是结果是:
fd: 0
或者
fd 2
可见,文件描述符的分配规则:在
fifiles_struct
数组当中,找到当前没有被使用的
最小的一个下标,作为新的文件描述符。