Chinaunix首页 | 论坛 | 博客
  • 博客访问: 408845
  • 博文数量: 82
  • 博客积分: 2600
  • 博客等级: 少校
  • 技术积分: 961
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-08 21:44
文章分类
文章存档

2013年(2)

2012年(56)

2010年(24)

我的朋友

分类: LINUX

2012-07-10 23:32:39

/proc文件接口笔记

最近阅读GPHY驱动源码,有运用到/proc文件来作为与内核通信的接口,所以闲暇时间简单整理下。

在次只记录简单的运用,不会深入到整个文件系统的注册实现。

主要数据结构:

struct proc_dir_entry;

接口

创建目录:

proc_mkdir()

proc_symlink()

创建文件(项):

create_proc_entry()

create_proc_read_entry()

删除项:

remove_proc_entry()

在创建entry之后,返回struct proc_dir_entry可是现实read_proc 和 write_proc来达到对文件的读写操作。


简单示例:

/*
 * helllo.c - Demonstrates module documentation.
 */

#include
#include
#include //copy_from_user()

#define DRIVER_AUTHOR "Jon"
#define DRIVER_DESC   "A sample driver"

// global
char version[64];
struct proc_dir_entry *proc_dir = NULL;
struct proc_dir_entry *proc_entry = NULL;


int hello_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data)
{
 int len = 0;

 len = strlen(version);
 if(len < off)
  return 0;
 
 if(count > len - off)
  count = len - off;
 
 memcpy(page+off, version+off, count);
 *eof = 1;

 return off + count;
}

int hello_write_proc(struct file *file, const char __user *buf, unsigned long count, void *data)
{
  int len = 0;
 
  len = sizeof(version);
  if( count < len )
   len = count;

  if(copy_from_user(version, buf, len))
   return -EFAULT;
  
  version[len] = 0;
 
  return len;
}

static int __init init_hello(void)
{
  proc_dir = proc_mkdir("driver/hello", NULL);
  if( !proc_dir )
  {
      printk(KERN_ERR "%s: Create proc directory (driver/hello) failed !!!\n", __func__);
      return -EFAULT;
  }
 
  proc_entry = create_proc_entry("version", 0660, proc_dir);
  if( !proc_entry )
  {
      printk(KERN_ERR "%s: Create proc directory (version) failed !!!\n", __func__);
      return -EFAULT;
  }
 
  strcpy(version, "1.1.0");
  proc_entry->read_proc = hello_read_proc;
  proc_entry->write_proc = hello_write_proc; 
 
     return 0;
}

static void __exit cleanup_hello(void)
{
   remove_proc_entry("version", proc_dir);
   remove_proc_entry("driver/hello", NULL); 
}
 
module_init(init_hello);
module_exit(cleanup_hello);
 
/* You can use strings, like this */

/* Get rid of taint message by declaring code as GPL. */
 
MODULE_LICENSE("GPL");
 
/* Or with defines, like this: */

MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
 
MODULE_SUPPORTED_DEVICE("testdevice");


参考:
http://www.ibm.com/developerworks/cn/linux/l-proc.html

阅读(2845) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~