kthread.c 689 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#kthread */
  2. #include <linux/delay.h> /* usleep_range */
  3. #include <linux/kernel.h>
  4. #include <linux/kthread.h>
  5. #include <linux/module.h>
  6. static struct task_struct *kthread;
  7. static int work_func(void *data)
  8. {
  9. u32 i = 0;
  10. while (!kthread_should_stop()) {
  11. pr_info("%u\n", i);
  12. usleep_range(1000000, 1000001);
  13. i++;
  14. if (i == 10)
  15. i = 0;
  16. }
  17. return 0;
  18. }
  19. static int myinit(void)
  20. {
  21. kthread = kthread_create(work_func, NULL, "mykthread");
  22. wake_up_process(kthread);
  23. return 0;
  24. }
  25. static void myexit(void)
  26. {
  27. /* Waits for thread to return. */
  28. kthread_stop(kthread);
  29. }
  30. module_init(myinit)
  31. module_exit(myexit)
  32. MODULE_LICENSE("GPL");