【Linux】文件描述符

  • 定义

文件描述符是用来访问文件的一个小整数,是操作系统访问特定文件的标志。

  • 用法

#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;
}

输出结果为:

通过上面的实践,我们不难发现,文件描述符的分配规则是:从最小的,未被使用的小整数开始分配。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值