kthreads.c 977 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#kthreads */
  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 *kthread1, *kthread2;
  7. static int work_func1(void *data)
  8. {
  9. int i = 0;
  10. while (!kthread_should_stop()) {
  11. pr_info("1 %d\n", i);
  12. usleep_range(1000000, 1000001);
  13. i++;
  14. if (i == 10)
  15. i = 0;
  16. }
  17. return 0;
  18. }
  19. static int work_func2(void *data)
  20. {
  21. int i = 0;
  22. while (!kthread_should_stop()) {
  23. pr_info("2 %d\n", i);
  24. usleep_range(1000000, 1000001);
  25. i++;
  26. if (i == 10)
  27. i = 0;
  28. }
  29. return 0;
  30. }
  31. static int myinit(void)
  32. {
  33. kthread1 = kthread_create(work_func1, NULL, "mykthread1");
  34. kthread2 = kthread_create(work_func2, NULL, "mykthread2");
  35. wake_up_process(kthread1);
  36. wake_up_process(kthread2);
  37. return 0;
  38. }
  39. static void myexit(void)
  40. {
  41. kthread_stop(kthread1);
  42. kthread_stop(kthread2);
  43. }
  44. module_init(myinit)
  45. module_exit(myexit)
  46. MODULE_LICENSE("GPL");