Linux - 基本内核模块中的proc_fs实现

时间:2015-09-07 10:53:32

标签: linux linux-kernel

所以我试图实现并看看模块如何在/proc中创建一个虚拟文件,这是我写的一个非常简单的代码:

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>

#define BUF_SIZE 48

struct proc_dir_entry *proc_entry,*root_dir=NULL;
char result_buffer[BUF_SIZE];
char before[BUF_SIZE];
int count,temp=1;

ssize_t write(struct file *f, const char __user *buf, size_t len, loff_t *off)
{ 
  printk(KERN_ERR "my4: Somebody toyed here\n");
  if (copy_from_user(result_buffer,buf,len))
    return -EFAULT;
  return len;
}
// this read implementation is just a fudge, i am just trying to get the grasp of basic concepts here
ssize_t read(struct file *f, char __user *buf, size_t c, loff_t *off)
{
  int len = 0;
  if (temp == 0) {
    temp = 1;
    return 0;
  }
  sprintf(before,"[%s]",result_buffer);
  if (count <= 1)
    sprintf(result_buffer,"my4 read %d\n",count++);
  else 
    sprintf(result_buffer,"my4 read again!! count=%d\n", count++);
  len = strlen(result_buffer);
  if (copy_to_user(buf, result_buffer, len)) return -EFAULT;
  printk(KERN_ERR "my4: page before=[%s]\n\t page after=[%s]\n", before, result_buffer);
  temp = 0;
  return len;
}

static const struct file_operations file_ops = {
  .owner = THIS_MODULE,
  .read  = read,
  .write = write
};

int init_my4(void) {
  count = 1;
  proc_entry = proc_create("my4", 438, NULL, &file_ops);
  strcpy(result_buffer, "initialized\n");

  if (proc_entry == NULL) {
    printk(KERN_ERR "my4: could not create proc entry\n");
    return -ENOMEM;
  }
  printk(KERN_INFO "my4: Module loaded successfully\n");

  return 0;
}

void unload_my4(void) {
  remove_proc_entry("my4",root_dir);
  printk(KERN_INFO "my4: Module unloaded successfully\n");
}

module_init(init_my4);
module_exit(unload_my4);
MODULE_LICENSE("GPL");

问题是BUF_SIZE只有48,如果我写的文件比文件更多,那就是:

echo "Lets write more than 48 bytes to the file and see if it breaks or overflows or if the kernel kills my process" > /proc/my4

现在当我cat /proc/my4时,我得到了:

my4: Somebody toyed here
[23482.029609] my4: page before=[[Lets write more than 48 bytes to the file and see if it breaks my4 read again!! count=3
]
     page after=[my4 read again!! count=3

我无法理解这里发生的事情是内核如何简单地忽略大于48字节的输入以及它在哪里? 我认为它会溢出segfault或者内核会终止进程!

0 个答案:

没有答案