Linux内核中的dup系统调用

发表于:2013-1-17 09:39

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:ce123    来源:51Testing软件测试网采编

  内核版本:2.6.14

  dup系统调用的服务例程为sys_dup函数,定义在fs/fcntl.c中。sys_dup()的代码也许称得上是最简单的之一了,但是就是这么一个简单的系统调用,却成就了linux系统最著名的一个特性:输入/输出重定向。sys_dup()的主要工作就是用来“复制”一个打开的文件号,并使两个文件号都指向同一个文件,下面我们来分析一下它的代码。

  1、sys_dup源码分析

asmlinkage long sys_dup(unsigned int fildes)//sys_dup函数的参数,即fildes,是文件描述符fd
{
 int ret = -EBADF;
 struct file * file = fget(fildes);//通过文件描述符找到对应的文件


 if (file)
  ret = dupfd(file, 0);//分配一个新的文件描述符fd,并将fd和file联系起来
 return ret;
}

  1.1 fget(fildes)

struct file fastcall *fget(unsigned int fd)
{
 struct file *file;
 struct files_struct *files = current->files;//获得当前进程的打开文件表


 rcu_read_lock();
 file = fcheck_files(files, fd);//根据fd从打开文件表files里取出相应的file结构变量
 if (file) {
  if (!rcuref_inc_lf(&file->f_count)) {  //增加引用
   /* File object ref couldn't be taken */
   rcu_read_unlock();
   return NULL;
  }
 }
 rcu_read_unlock();


 return file;
}
static inline struct file * fcheck_files(struct files_struct *files, unsigned int fd)
{
 struct file * file = NULL;
 struct fdtable *fdt = files_fdtable(files);


 if (fd < fdt->max_fds)
  file = rcu_dereference(fdt->fd[fd]);
 return file;
}

  1.2 dupfd(file, 0)

static int dupfd(struct file *file, unsigned int start)
{
 struct files_struct * files = current->files;
 struct fdtable *fdt;
 int fd;


 spin_lock(&files->file_lock);
 fd = locate_fd(files, file, start);//分配文件描述符
 if (fd >= 0) {
  /* locate_fd() may have expanded fdtable, load the ptr */
  fdt = files_fdtable(files);//获得文件描述符表
  FD_SET(fd, fdt->open_fds);//设置打开文件标记
  FD_CLR(fd, fdt->close_on_exec);
  spin_unlock(&files->file_lock);
  fd_install(fd, file);//建立fd和file的联系,之后通过fd就可以找到file
 } else {
  spin_unlock(&files->file_lock);
  fput(file);
 }


 return fd;
}

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号