设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

Linux内核驱动模块中写文件

2012-6-6 17:08| 发布者: 红黑魂| 查看: 2339| 评论: 0|来自: 比特网

摘要:   最近项目中遇到一个问题,需要在驱动ko文件中写文件记录log,网上google了半天,要么不能用,要么直接编译不通过,最后参考内核源码linux-2.6.38/drivers/staging/spectra/lld_emu.c才搞定,主要如下:  1.我内 ...

  最近项目中遇到一个问题,需要在驱动ko文件中写文件记录log,网上google了半天,要么不能用,要么直接编译不通过,最后参考内核源码linux-2.6.38/drivers/staging/spectra/lld_emu.c才搞定,主要如下:

  1.我内核版本为2.6.38,编译器gcc version 4.4.1 (Sourcery G++ Lite 2009q3-67);

  2.使用网上说的sys_open编译没问题,加载时会提示unknown symbol错误,估计是没有EXPORT_SYMBOL,所以不能在ko文件中使用;

  3.使用网上一个filp_open例子,里面还调用了ioctl相关,直接编译错误,去除相关错误后,又加载错误;

  4.用cscope搜索调用filp_open相关地方,找到drivers/staging/spectra/lld_emu.c里面有一个int emu_write_mem_to_file(void),copy出来,几乎不用修改直接可以使用,源码如下:

  点击(此处)折叠或打开

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  static int write_log_file(char *filename, char *data_w) {

  mm_segment_t fs;

  struct file *nef_filp = NULL;

  struct inode *inode = NULL;

  loff_t nef_size = 0;

  loff_t tmp_file_offset;

  ssize_t nwritten;

  int rc = -EINVAL;

  int str_len;

  fs = get_fs();

  set_fs(get_ds());

  nef_filp = filp_open(filename, O_CREAT | O_RDWR, 0);

  if (IS_ERR(nef_filp)) {

  printk(KERN_ERR "filp_open error: "

  "Unable to open nand emu file!\n");

  return PTR_ERR(nef_filp);

  }

  if (nef_filp->f_path.dentry) {

  inode = nef_filp->f_path.dentry->d_inode;

  } else {

  printk(KERN_ERR "Invalid " "nef_filp->f_path.dentry value!\n");

  goto out;

  }

  nef_size = i_size_read(inode->i_mapping->host);

  if (nef_size < 0) {

  printk(KERN_ERR "Invalid "

  "nand emu file size: 0x%llx\n", nef_size);

  goto out;

  } else {

  printk(KERN_ERR "nand emu file size: ""%lld\n", nef_size);

  }

  str_len = strlen(data_w) + 1;

  tmp_file_offset = nef_size;

  nwritten = vfs_write(nef_filp,

  (char __user *)data_w,

  str_len, &tmp_file_offset);

  if (nwritten < str_len) {

  printk(KERN_ERR "%s, Line %d - "

  "nand emu file partial write: "

  "%d bytes\n", __FILE__, __LINE__, (int)nwritten);

  goto out;

  }

  rc = 0;

  out:

  filp_close(nef_filp, current->files);

  set_fs(fs);

  return rc;

  }

  在合适处调用如write_log_file("/root/kernel_reboot.txt", "rebooting…\n\n")即可。


酷毙
1

雷人

鲜花

鸡蛋
1

漂亮

刚表态过的朋友 (2 人)

  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部