现在的位置: 首页 > 综合 > 正文

Linux内核读写文件

2013年10月06日 ⁄ 综合 ⁄ 共 4777字 ⁄ 字号 评论关闭

drivers/mtd/nandsim.c

<1>:打开文件

  cfile = filp_open(cache_file, O_CREAT | O_RDWR | O_LARGEFILE, 0600);
  if (IS_ERR(cfile))
   return PTR_ERR(cfile);

  if (!cfile->f_op || (!cfile->f_op->read && !cfile->f_op->aio_read)) {
   NS_ERR("alloc_device: cache file not readable/n");
   err = -EINVAL;
   goto err_close;
  }
  if (!cfile->f_op->write && !cfile->f_op->aio_write) {
   NS_ERR("alloc_device: cache file not writeable/n");
   err = -EINVAL;
   goto err_close;
  }

<2>:读文件

static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
{
 mm_segment_t old_fs;
 ssize_t tx;
 int err, memalloc;

 err = get_pages(ns, file, count, *pos);
 if (err)
  return err;
 
old_fs = get_fs();
 set_fs(get_ds());    //将地址空间设置为内核空间,防止vfs_read返回失败
 memalloc = set_memalloc();
 tx = vfs_read(file, (char __user *)buf, count, pos);
 clear_memalloc(memalloc);
 set_fs(old_fs);
 put_pages(ns);
 return tx;
}

<3>:写文件

static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
{
 mm_segment_t old_fs;
 ssize_t tx;
 int err, memalloc;

 err = get_pages(ns, file, count, *pos);
 if (err)
  return err;
 
old_fs = get_fs();
 set_fs(get_ds());  //#define get_ds() (KERNEL_DS)
 memalloc = set_memalloc();
 tx = vfs_write(file, (char __user *)buf, count, pos);
 clear_memalloc(memalloc);
 set_fs(old_fs);
 put_pages(ns);
 return tx;
}

 

 

 

抱歉!评论已关闭.