我的代码在读取和写入设备文件时有什么问题
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此行看起来错误:
您仅复制
sizeof(*buf)
字节,这可能是 4 或 8 字节,具体取决于架构。您应该使用
count
参数。This line looks wrong:
You only copy
sizeof(*buf)
bytes, which is likely 4 or 8 bytes depending on the architecture.You should use the
count
argument.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
.