How to send Notification from Kernel to user space application using SYSFS

I'm working in an USB ACM driver, "where i need to send notification from kernel space to user space application for invoking a call back function". I'm not much aware of using kernel to user interfaces in code. how well can sysfs help for this scenario. Please send some sample code to use sysfs so that I'll get an idea to implement in my code. I could not find it anywhere. Also pls tell anyother easy way to achieve kernel to user space notification. Thanks in advance.

Upvotes: 0

Views: 3944

Answers (2)

Alexey Polonsky
Alexey Polonsky

Reputation: 1201

Another alternative would be to use eventfd. You create eventfd, pass the integer file descriptor to kernel space (e.g. through sysfs, or ioctl), then convert the file descriptor you got from user space to eventfd_ctx in kernel space. This is it - you have your notification channel.

User space

#include <sys/eventfd.h>

int efd = eventfd(0, 0);
// pass 'efd' to kernel space

Kernel space

#include <linux/eventfd.h>

// Set up
int efd = /* get from user space - sysfs/ioctl/write/... */;
struct eventfd_ctx* efd_ctx = eventfd_ctx_fdget(efd);

// Signal user space
eventfd_signal(efd_ctx, 1);

// Tear down
eventfd_ctx_put(efd_ctx);

Upvotes: 1

whh4000
whh4000

Reputation: 955

My suggestion would be to create a sysfs interface to your kernel driver that userspace can access. Each sysfs attribute if created with the correct properties can be read like a file from userspace. You can then use the poll function from userspace to poll for an action on that file. To trigger this action from Kernel space, you can use the sysfs_notify function on your attribute and it will cause your userspace code to wake up. Here is how I would do it

Kernel 1. Create Kobject or attach an attribute to a previous kobject 2. When you want to signal userspace call sysfs_notify on the kobject and attribute

Userspace

  1. Create a new thread that will block while waiting for the sysfs_notify
  2. Open the sysfs attribute from this thread
  3. poll the attribute, once sysfs_notify from the kernel is called it will unblock your poll
  4. call your event handling function

Upvotes: 1

Related Questions