FileDescriptors源码阅读


涉及的文件主要有file.hsysfile.c


file.h

file结构体表示系统中的一个打开文件实例:

struct file {
  enum { FD_NONE, FD_PIPE, FD_INODE, FD_DEVICE } type;
  int ref; // reference count
  char readable;
  char writable;
  struct pipe *pipe; // FD_PIPE
  struct inode *ip;  // FD_INODE and FD_DEVICE
  uint off;          // FD_INODE
  short major;       // FD_DEVICE
};

type区分类型,ref用于跟踪有多少个文件描述符引用该结构,后面两个读写标志位,off为偏移量。

inode结构为磁盘inode的内存缓存副本:

// in-memory copy of an inode
struct inode {
  uint dev;           // Device number
  uint inum;          // Inode number
  int ref;            // Reference count
  struct sleeplock lock; // protects everything below here
  int valid;          // inode has been read from disk?

  short type;         // copy of disk inode
  short major;
  short minor;
  short nlink;
  uint size;
  uint addrs[NDIRECT+1];
};

sysfile.c

这段代码中只看fdalloc函数,这个函数是文件描述符的分配函数。在此之前,先看一下proc.h中的定义:

再回来看这个函数:

它首先获取当前进程,然后遍历当前进程的文件描述符,NOFILE定义在param.h中:

如果发现空槽位,则进行分配。