【问题标题】:whats wrong with my code in reading and writing in device file我的代码在设备文件中读写有什么问题
【发布时间】:2012-01-26 10:43:12
【问题描述】:

我是 linux 新手,正在制作一个模块,用户可以在其中读取和写入设备文件。以下是我的代码,其中读取工作正常,但写入功能不正常。

MODULE_LICENSE("DUAL BSD/GPL");

char message[80];
char *msg_ptr;

int dev_major = 0;
int dev_minor = 0;

struct cdev *cdev;

ssize_t dev_read(struct file *filp,char __user *buf,size_t count,loff_t *offset)
{
int i;
i=copy_to_user(buf,msg_ptr,count);
 printk(KERN_ALERT"buff:%s",buf);


return 0;
 }
  ssize_t dev_write(struct file *filp,const char __user *buf,size_t count,loff_t *offset)
{
  int j;
    msg_ptr = kmalloc(sizeof(*buf),GFP_KERNEL);
    copy_from_user(msg_ptr,buf,sizeof(*buf));
 //printk(KERN_ALERT"msg_ptr:%s",msg_ptr);
  return 0;
      }

当我创建一个 char 节点然后使用 echo hi >/dev/my_dev 然后它会打印 hi 但会无限写入,如 /var/log/messages 中所示。

【问题讨论】:

    标签: c linux kernel-module


    【解决方案1】:

    这行看起来不对:

    copy_from_user(msg_ptr, buf, sizeof(*buf));
    

    您只复制 sizeof(*buf) 字节,这可能是 4 或 8 个字节,具体取决于架构。

    您应该使用count 参数。

    【讨论】:

    • 它是指向对象的大小,而不是指针。所以更糟糕的是:sizeof(*buf) 是 1。
    • copy_from_user(msg_ptr,buf,count);我已经使用它但问题仍然存在............任何更多的建议......请帮助
    【解决方案2】:

    dev_write 应该返回写入的字节数。
    当你返回 0 时,Linux 知道你写了 0 个字节,然后再次调用你写剩下的。再说一遍……

    dev_read 也一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      相关资源
      最近更新 更多