poll.c 2.1 KB

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