内核sleep schedule_timeout

本文介绍了一个简单的Linux内核模块示例,该模块创建了一个内核线程(kthread),并演示了如何使线程周期性地执行任务。通过使用`kthread_create`函数创建线程,并在循环中调用`SLEEP_MILLI_SEC`宏来实现休眠,最终打印当前的时间戳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自http://blog.youkuaiyun.com/guowenyan001/article/details/39230181
  1. #include <linux/module.h>  
  2. #include <linux/kernel.h>  
  3. #include <linux/types.h>  
  4. #include <linux/kthread.h>  
  5. #include <linux/err.h>  
  6.   
  7.   
  8. MODULE_VERSION("1.0.0_0");  
  9. MODULE_LICENSE("GPL");  
  10. MODULE_AUTHOR("gwy");  
  11.   
  12.   
  13.   
  14. #ifndef SLEEP_MILLI_SEC  
  15. #define SLEEP_MILLI_SEC(nMilliSec) \  
  16.     do { \  
  17.         long timeout = (nMilliSec) * HZ /1000; \  
  18.         while (timeout > 0) \  
  19.         { \  
  20.             timeout = schedule_timeout(timeout); \  
  21.         } \  
  22.     }while (0);  
  23. #endif  
  24.   
  25.   
  26. struct task_struct* thread = NULL;  
  27.   
  28. void thread_proc(void* arg)  
  29. {  
  30.     struct timespec ts;    
  31.   
  32.     //set_current_state(TASK_UNINTERRUPTIBLE);  
  33.     while(!kthread_should_stop())  
  34.     {  
  35.         ts = current_kernel_time();    
  36.         printk("thread_proc:%s. time:%ld\n", (char*)arg, ts.tv_sec);  
  37.           
  38.         SLEEP_MILLI_SEC(1000);  
  39.     }  
  40. }  
  41.   
  42. static int init_marker(void)  
  43. {  
  44.     int err;  
  45.   
  46.     printk("init marker.\n");  
  47.   
  48.     thread = kthread_create(thread_proc, "thread arg""my_thread%d", 0);  
  49.     if (IS_ERR(thread))  
  50.     {  
  51.         err = PTR_ERR(thread);  
  52.         printk("kthread_create fail.\n");  
  53.         return err;  
  54.     }  
  55.   
  56.     wake_up_process(thread);  
  57.   
  58.     printk("thread create.\n");  
  59.   
  60.     return 0;  
  61. }  
  62.   
  63. static void exit_marker(void)  
  64. {  
  65.     if (thread)  
  66.     {  
  67.         kthread_stop(thread);  
  68.         thread = NULL;  
  69.         printk("thread stop.\n");  
  70.     }  
  71.   
  72.     printk("exit marker.\n");  
  73. }  
  74.   
  75.   
  76. module_init(init_marker);  
  77. module_exit(exit_marker); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值