Linux内核:从内核空间在用户空间中调用回调函数 [英] Linux Kernel: invoke call back function in user space from kernel space

查看:863
本文介绍了Linux内核:从内核空间在用户空间中调用回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Linux用户空间应用程序.我想从内核空间在用户空间区域调用注册的回调函数.

I am writing Linux user space application. where I want to invoke registered callback function in user space area from the kernel space.

即中断到达GPIO引脚(按下开关事件),并且已注册的函数在用户空间中被调用.

i.e. interrupt arriving on GPIO pin(switch press event) and registered function getting called in user space.

有什么方法可以做到这一点.

is there any method is available to do this.

谢谢

推荐答案

经过大量挖掘,我发现了下面的代码,对我来说很完美.

处理来自GPIO的中断 在许多情况下,GPIO输入可以配置为在输入时产生中断 更改状态,使您可以等待中断而不是轮询 低效的软件循环.如果GPIO位可以产生中断,则文件边缘 存在.最初,它的值是none,这意味着它不会产生中断. 要启用中断,可以将其设置为以下值之一: •上升:上升沿中断 •下降:下降沿中断 •两者:同时在上升沿和下降沿中断 •无:无中断(默认) 您可以使用带POLLPRI作为事件的poll()函数来等待中断.如果 您要等待GPIO 48的上升沿,首先启用中断:

Handling interrupts from GPIO In many cases, a GPIO input can be configured to generate an interrupt when it changes state, which allows you to wait for the interrupt rather than polling in an inefficient software loop. If the GPIO bit can generate interrupts, the file edge exists. Initially, it has the value none , meaning that it does not generate interrupts. To enable interrupts, you can set it to one of these values: • rising: Interrupt on rising edge • falling: Interrupt on falling edge • both: Interrupt on both rising and falling edges • none: No interrupts (default) You can wait for an interrupt using the poll() function with POLLPRI as the event. If you want to wait for a rising edge on GPIO 48, you first enable interrupts:

#echo 48>/sys/class/gpio/export

#echo上升>/sys/class/gpio/gpio48/edge

然后,使用poll()等待更改,如下面的代码示例所示:

Then, you use poll() to wait for the change, as shown in this code example:

 #include <stdio.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <poll.h>>

 int main(void) {

         int f;
         struct pollfd poll_fds [1];
         int ret;
         char value[4];
         int n;

         f = open("/sys/class/gpio/gpio48", O_RDONLY);
         if (f == -1) {
              perror("Can't open gpio48");
              return 1;
         }

         poll_fds[0].fd = f;
         poll_fds[0].events = POLLPRI | POLLERR;

         while (1) {
              printf("Waiting\n");

              ret = poll(poll_fds, 1, -1);
              if (ret > 0) {
                  n = read(f, &value, sizeof(value));
                  printf("Button pressed: read %d bytes, value=%c\n", n, value[0]);
              }
         }     
      return 0; 
}

这篇关于Linux内核:从内核空间在用户空间中调用回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆