编写内核模块,用工作队列实现周期打印helloworld
时间: 2023-10-23 21:27:39 浏览: 50
首先,需要编写内核模块的代码。以下是一个简单的例子,只包含一个初始化函数和一个退出函数。
```c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
static struct workqueue_struct *queue;
static struct delayed_work hello_work;
static void hello_func(struct work_struct *work)
{
printk(KERN_INFO "Hello World!\n");
schedule_delayed_work(&hello_work, msecs_to_jiffies(1000));
}
static int __init hello_init(void)
{
queue = create_singlethread_workqueue("hello_queue");
INIT_DELAYED_WORK(&hello_work, hello_func);
schedule_delayed_work(&hello_work, msecs_to_jiffies(1000));
return 0;
}
static void __exit hello_exit(void)
{
cancel_delayed_work_sync(&hello_work);
destroy_workqueue(queue);
}
module_init(hello_init);
module_exit(hello_exit);
```
以上代码使用了工作队列和延迟工作来实现周期性地打印 “Hello World!”。在初始化函数 `hello_init()` 中,创建了一个单线程的工作队列,并初始化了一个延迟工作 `hello_work`,并将其加入到工作队列中,设置了延迟时间为 1000 毫秒。在 `hello_func()` 函数中,打印了一条信息,并再次将 `hello_work` 加入到工作队列中,以达到周期性执行的目的。在退出函数 `hello_exit()` 中,取消了 `hello_work`,并销毁了工作队列。
编译内核模块的命令如下:
```sh
make -C /lib/modules/$(uname -r)/build M=$PWD modules
```
加载内核模块的命令如下:
```sh
sudo insmod hello.ko
```
可以通过 `dmesg` 命令查看内核日志,看到周期性打印的 “Hello World!”。卸载内核模块的命令如下:
```sh
sudo rmmod hello
```