Linux内核模块,创建LIFO设备

马里奥

我正在尝试编写一个简单的内核模块(char设备),该模块充当内存,确切地说是一个LIFO(堆栈)。当前代码如下所示:

#include <linux/module.h> 
//and the rest of the includes and defines go here

struct virtual_device{ char data[STACK_SIZE];
}stack;// my stack data is stored in this structure

int device_open(struct inode *inode, struct file *filp){return 0;}

int device_release(struct inode *inode, struct file *filp){return 0;}

ssize_t device_write(struct file *filp, const char *buf, size_t count, loff_t *offset){
  ret = copy_from_user(stack.data,buf,count);
  return ret;
}

ssize_t device_read(struct file *filp, char* buf, size_t count, loff_t *offset){
  ret = copy_to_user(buf, stack.data,count);
  return ret; 
}

struct file_operations fops = {
  .open = device_open,
  .write = device_write,
  .read = device_read,
  .release = device_release
};

static int driver_entry( void ){
  //this part of the code is pretty standard, 
  //module initialization , major number generation and so on
}

static void driver_exit( void ){
  //char device deletion, unregister...
}

module_init(driver_entry);
module_exit(driver_exit);

在阅读了有关copy_to_user和copy_from_user函数的一些知识后,我的印象是我可以循环使用它们并处理文件指针,以更改设备的写入顺序。我将写入功能更改为:

ssize_t device_write(struct file *filp, const char *buf, size_t count,loff_t *offset){
  char *temp;
  int i=1;

  while(i<= count){
    temp = buf + count - i;
    ret = copy_from_user(stack.data,temp,1);
    printk(KERN_INFO "Writing to device");      
    i +=1;
  } 
return ret; 
}

基本上,我试图从一个字符到另一个字符,从后到前从一个字符开始复制,希望当我阅读消息时,它会被反转(您知道LIFO是如何从最后一个条目读取到第一个条目的)。

但是,当我尝试使用该设备时会发疯:即使我将其写入``hola'',dmesg日志也会显示50条``正在写入设备''消息,而当我尝试从中读取时,我得到的只是。有人可以指出我忽略的地方吗?我的尝试太天真了吗?

Ming

因为u始终返回0(假设copy_from_user不会失败)。因此,VFS认为您的驱动程序未接受(编写)任何内容。而且VFS会继续尝试写...。这就是为什么您不断收到“正在写入设备”消息的原因。

while(i<= count){

    temp = buf + count - i;

    ret = copy_from_user(stack.data,temp,1); // ==> U keep writing data to same position -> stack.data[0]

    printk(KERN_INFO "Writing to device");      
    i +=1;
} 


ssize_t device_read(struct file *filp, char* buf, size_t count, loff_t *offset){
  ret = copy_to_user(buf, stack.data,count);//==> U should return whatever u have in "data" instead of use "count" which might be pretty big.
  return ret; 
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章