我的代码在读取和写入设备文件时有什么问题

发布于 2024-12-29 05:41:23 字数 746 浏览 0 评论 0原文

我是 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 中所示。

I am new to linux and was making a module in which user can read as well as write to a device file.the following is my code where read is working fine but not the write function.

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;
      }

when i make a char node and then use echo hi >/dev/my_dev then it prints hi but writes infintely as seen in /var/log/messages.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何其悲哀 2025-01-05 05:41:23

此行看起来错误:

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

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

您应该使用 count 参数。

This line looks wrong:

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

You only copy sizeof(*buf) bytes, which is likely 4 or 8 bytes depending on the architecture.

You should use the count argument.

忘你却要生生世世 2025-01-05 05:41:23

dev_write 应返回写入的字节数。
当你返回0时,Linux知道你写了0个字节,并再次调用你写其余的字节。再说一次...

对于 dev_read 来说也是如此。

dev_write should return the number of bytes written.
When you return 0, Linux understand you wrote 0 bytes, and calls you again to write the rest. And again...

Same for dev_read.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文