- 论坛徽章:
- 0
|
今天白天没办法上网, 就闲着, 看《Linux内核设计与实现》,刚好看到内核线程的时候, 无聊就写了个简单的代码. 就把我系统给弄挂了.
(鄙人在CU的第一个帖子.希望大家不吝赐教.我也准备好了被拍砖的心里准备了.^_^)
最开始的源代码如下: 我最开始想的是, insmod 的时候开始执行线程, rmmod 的时候, 就结束线程.- #include <linux/module.h>
- #include <linux/kernel.h>
- #include <linux/sched.h>
- #include <linux/init.h>
- #include <linux/kthread.h>
- static struct task_struct *tsk;
- static int my_thread_func(void *data)
- {
- int index = 0;
-
- while (1) {
- printk(KERN_NOTICE"my_thread_func, index = %d!\n", index ++);
- sleep(1);
- }
- return 0;
- }
- static int __init kernel_thread_init(void)
- {
- printk(KERN_NOTICE"kernel_thread_init!\n");
- tsk = kthread_create(my_thread_func, NULL, "my_thread");
- if (!IS_ERR(tsk))
- wake_up_process(tsk);
-
- return 0;
- }
- static void __exit kernel_thread_exit(void)
- {
- printk(KERN_NOTICE"print_task_exit!\n");
- if (!IS_ERR(tsk)
- kthread_stop(tsk);
-
- return;
- }
- module_init(kernel_thread_init);
- module_exit(kernel_thread_exit);
- MODULE_LICENSE("Dual BSD/GPL");
复制代码 编译后, 直接 insmod, 发现, 这条命令还没执行完, 系统就完全没反应了. ctrl+c, 啥的都没有反应. 只能关电.
后面,想想, 线程处理函数 my_thread_func 函数, 这样处理, 不就把 CPU 全被霸占了.就修改了下 my_thread_func 代码. 代码如下:- static int my_thread_func(void *data)
- {
- int index = 0;
-
- while (index < 5) {
- printk(KERN_NOTICE"my_thread_func, index = %d!\n", index ++);
- }
- return 0;
- }
复制代码 然后编译, 执行 insmod 命令, 系统OK. 也可以 rmmod.
执行命令 dmesg | tail -10 可以看到预期的5条打印信息.
my_thread_func, index = 0!
my_thread_func, index = 1!
my_thread_func, index = 2!
my_thread_func, index = 3!
my_thread_func, index = 4!
请问下, 在不使用内核定时器的前提下, 才能实现,
insmod 的时候开始执行线程, rmmod 的时候, 就结束线程.
|
|