How to add poll function to the kernel module code?

You can find some good examples in kernel itself. Take a look at next files:

To add poll() function to your code follow next steps.

  1. Include needed headers:

     #include <linux/wait.h>
     #include <linux/poll.h>
    
  2. Declare waitqueue variable:

     static DECLARE_WAIT_QUEUE_HEAD(fortune_wait);
    
  3. Add fortune_poll() function and add it (as .poll callback) to your file operations structure:

     static unsigned int fortune_poll(struct file *file, poll_table *wait)
     {
         poll_wait(file, &fortune_wait, wait);
         if (new-data-is-ready)
             return POLLIN | POLLRDNORM;
         return 0;
     }
    
     static const struct file_operations proc_test_fops = {
         ....
         .poll = fortune_poll,
     };
    

    Note that you should return POLLIN | POLLRDNORM if you have some new data to read, and 0 in case there is no new data to read (poll() call timed-out). See man 2 poll for details.

  4. Notify your waitqueue once you have new data:

     wake_up_interruptible(&fortune_wait);
    

That’s the basic stuff about implementing poll() operation. Depending on your task, you may be needed to use some waitqueue API in your .read function (like wait_event_interruptible()).


See also related question: Implementing poll in a Linux kernel module.

Leave a Comment