poll.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#poll */
  2. #include <linux/debugfs.h>
  3. #include <linux/delay.h> /* usleep_range */
  4. #include <linux/errno.h> /* EFAULT */
  5. #include <linux/fs.h>
  6. #include <linux/jiffies.h>
  7. #include <linux/kernel.h> /* min */
  8. #include <linux/kthread.h>
  9. #include <linux/module.h>
  10. #include <linux/poll.h>
  11. #include <linux/printk.h> /* printk */
  12. #include <linux/uaccess.h> /* copy_from_user, copy_to_user */
  13. #include <linux/wait.h> /* wait_queue_head_t, wait_event_interruptible, wake_up_interruptible */
  14. #include <uapi/linux/stat.h> /* S_IRUSR */
  15. static char readbuf[1024];
  16. static size_t readbuflen;
  17. static struct dentry *debugfs_file;
  18. static struct task_struct *kthread;
  19. static wait_queue_head_t waitqueue;
  20. static ssize_t read(struct file *filp, char __user *buf, size_t len, loff_t *off)
  21. {
  22. ssize_t ret;
  23. if (copy_to_user(buf, readbuf, readbuflen)) {
  24. ret = -EFAULT;
  25. } else {
  26. ret = readbuflen;
  27. }
  28. /* This is normal pipe behaviour: data gets drained once a reader reads from it. */
  29. /* https://stackoverflow.com/questions/1634580/named-pipes-fifos-on-unix-with-multiple-readers */
  30. readbuflen = 0;
  31. return ret;
  32. }
  33. /* If you return 0 here, then the kernel will sleep until an event happens in the queue.
  34. *
  35. * This gets called again every time an event happens in the wait queue.
  36. */
  37. unsigned int poll(struct file *filp, struct poll_table_struct *wait)
  38. {
  39. poll_wait(filp, &waitqueue, wait);
  40. if (readbuflen)
  41. return POLLIN;
  42. else
  43. return 0;
  44. }
  45. static int kthread_func(void *data)
  46. {
  47. while (!kthread_should_stop()) {
  48. readbuflen = snprintf(readbuf, sizeof(readbuf), "%llu", (unsigned long long)jiffies);
  49. usleep_range(1000000, 1000001);
  50. wake_up(&waitqueue);
  51. }
  52. return 0;
  53. }
  54. static const struct file_operations fops = {
  55. .owner = THIS_MODULE,
  56. .read = read,
  57. .poll = poll
  58. };
  59. static int myinit(void)
  60. {
  61. debugfs_file = debugfs_create_file(
  62. "lkmc_poll", S_IRUSR | S_IWUSR, NULL, NULL, &fops);
  63. init_waitqueue_head(&waitqueue);
  64. kthread = kthread_create(kthread_func, NULL, "mykthread");
  65. wake_up_process(kthread);
  66. return 0;
  67. }
  68. static void myexit(void)
  69. {
  70. kthread_stop(kthread);
  71. debugfs_remove(debugfs_file);
  72. }
  73. module_init(myinit)
  74. module_exit(myexit)
  75. MODULE_LICENSE("GPL");