给我写一个内核模块
时间: 2024-02-13 21:05:26 浏览: 20
好的,以下是一个简单的内核模块示例,它将创建一个名为 "hello" 的 proc 文件,并在加载时打印一条消息到系统日志中:
```
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#define PROC_NAME "hello"
static ssize_t hello_read(struct file *file, char __user *buffer, size_t count, loff_t *pos)
{
char *msg = "Hello, world!\n";
size_t len = strlen(msg);
if (*pos >= len)
return 0;
if (count > len - *pos)
count = len - *pos;
if (copy_to_user(buffer, msg + *pos, count))
return -EFAULT;
*pos += count;
return count;
}
static const struct file_operations hello_fops = {
.owner = THIS_MODULE,
.read = hello_read,
};
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, world!\n");
if (!proc_create(PROC_NAME, 0, NULL, &hello_fops))
return -ENOMEM;
return 0;
}
static void __exit hello_exit(void)
{
remove_proc_entry(PROC_NAME, NULL);
printk(KERN_INFO "Goodbye, world!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple example Linux module.");
```
您需要将此代码保存到名为 "hello.c" 的文件中,并使用 "make" 命令编译该模块。然后使用 "insmod hello.ko" 命令加载模块。如果一切顺利,您应该能够在系统日志中看到 "Hello, world!" 和 "Goodbye, world!" 消息,并且您可以使用 "cat /proc/hello" 命令读取 "Hello, world!" 的输出。