首页 > 代码库 > 设备驱动基础学习--/proc下增加节点

设备驱动基础学习--/proc下增加节点

#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static struct proc_dir_entry *proc_root;
static struct proc_dir_entry *proc_entry;
#define USER_ROOT_DIR "fellow_root"
#define USER_ENTRY "fellow_entry"
#define INFO_LEN 16
char *info;
static int proc_fellow_show(struct seq_file *m, void *v)
{

  seq_printf(m, "%s\n",info);
  return 0;
}

static int proc_fellow_open(struct inode *inode, struct file *file)
{
  return single_open(file, proc_fellow_show, NULL);
}

static ssize_t proc_fellow_write(struct file *file, const char __user *buffer,  size_t count, loff_t *f_pos)
{
   if ( count > INFO_LEN)
  return -EFAULT;
  if(copy_from_user(info, buffer, count))
  {
    return -EFAULT;
  }
  return count;
}
static const struct file_operations fellow_proc_fops = {
.owner = THIS_MODULE,
.open = proc_fellow_open,
.read = seq_read,
.write = proc_fellow_write,
.llseek = seq_lseek,
.release = single_release,
};

static int fellow_create_proc_entry(void)
{
  int error = 0;
  proc_root = proc_mkdir(USER_ROOT_DIR, NULL);
  if (NULL==proc_root)
  {
    printk(KERN_ALERT"Create dir /proc/%s error!\n", USER_ROOT_DIR);
    return -ENOMEM;
  }
  printk(KERN_INFO"Create dir /proc/%s\n", USER_ROOT_DIR);

  // proc_entry =create_proc_entry(USER_ENTRY, 0666, proc_root);
  proc_entry = proc_create(USER_ENTRY, 0666, proc_root, &fellow_proc_fops);
  if (NULL ==proc_entry)
  {
    printk(KERN_ALERT"Create entry %s under /proc/%s error!\n", USER_ENTRY,USER_ROOT_DIR);
    error = -ENOMEM;
    goto err_out;

  }

//proc_entry->write_proc= fellow_writeproc;
//proc_entry->read_proc = fellow_readproc;
  printk(KERN_INFO"Create /proc/%s/%s\n", USER_ROOT_DIR,USER_ENTRY);

  return 0;
err_out:
//proc_entry->read_proc = NULL;
//proc_entry->write_proc= NULL;
  remove_proc_entry(USER_ENTRY, proc_root);
  remove_proc_entry(USER_ROOT_DIR, NULL);
  return error;
}
static int fellowproc_init(void)
{
  int ret = 0;
  printk("fellowproc_init\n");

  info = kmalloc(INFO_LEN * sizeof(char), GFP_KERNEL);
  if (!info)
  {
    ret = -ENOMEM;
    goto fail;
  }
  memset(info, 0, INFO_LEN);
  fellow_create_proc_entry();
  return 0;
fail:
  return ret;
}

static void fellowproc_exit(void)
{
  kfree(info);

  remove_proc_entry(USER_ENTRY, proc_root);
  remove_proc_entry(USER_ROOT_DIR, NULL);
}

MODULE_AUTHOR("fellow");
MODULE_LICENSE("GPL");
module_init(fellowproc_init);
module_exit(fellowproc_exit);

运行结果如下:

技术分享

 

设备驱动基础学习--/proc下增加节点