【发布时间】:2020-02-28 03:32:43
【问题描述】:
我开发了一个简单的linux内核模块:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
ssize_t exer_open(struct inode *pinode, struct file *pfile) {
return 0;
}
ssize_t exer_read(struct file *pfile, char __user *buffer, size_t length, loff_t *offset) {
return 0;
}
ssize_t exer_write(struct file *pfile, const char __user *buffer, size_t length, loff_t *offset) {
return length;
}
ssize_t exer_close(struct inode *pinode, struct file *pfile) {
return 0;
}
struct file_operations exer_file_operations = {
.owner = THIS_MODULE,
.open = exer_open,
.read = exer_read,
.write = exer_write,
.release = exer_close,
};
int exer_simple_module_init(void) {
printk(KERN_ALERT "Inside the %s function\n", __FUNCTION__);
register_chrdev(240, "Simple Char Drv", &exer_file_operations);
return 0;
}
void exer_simple_module_exit(void) {
unregister_chrdev(240, "Simple Char Drv");
}
module_init(exer_simple_module_init);
module_exit(exer_simple_module_exit);
我使用insmod 命令将此模块插入内核没有任何问题。
我想用这个模块来打印我也开发的用户空间程序发送给它的消息:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
int main()
{
int ret, fd;
char stringToSend[] = "Hello World !";
fd = open("/dev/char_device", O_RDWR); // Open the device with read/write access
if (fd < 0)
{
perror("Failed to open the device...");
return errno;
}
ret = write(fd, stringToSend, strlen(stringToSend)); // Send the string to the LKM
if (ret < 0)
{
perror("Failed to write the message to the device.");
return errno;
}
return 0;
}
当我使用tail -f /var/log/messages 命令执行程序并检查内核日志时,我可以看到:user.alert kernel: Inside the exer_read function 但我看不到消息“Hello World!”
我不知道我在这里缺少什么,尤其是我仍然是开发模块和使用它的初学者。请帮帮我!
【问题讨论】:
-
您希望在哪里看到消息“Hello World!”?您没有打印它,也没有为此做任何事情。
-
我该怎么做?如何从我的用户空间程序传递此消息(“Hello World!”)以便写入模块的文件设备并在我录制
tail -f /var/log/messages或dmesg时打印? -
您的字符串被传递给
buffer参数中的exer_read函数。在内核中对它进行任何操作之前,您必须使用copy_from_user函数复制它。 -
所以我必须在
exer_read函数中添加copy_from_user函数? -
对不起,我弄错了,我的意思是读函数中的
copy_to_user(和写函数中的copy_from_user。)但是是的,你需要调用这些函数来在用户空间之间复制数据和内核。我强烈建议在尝试构建驱动程序之前阅读这些内容。一本好书(虽然有点老了)是《Linux 设备驱动程序》。
标签: linux-kernel c