(十一)linux之poll轮询

目录

        • (一)poll轮询的作用
        • (二)poll轮询相关的接口
        • (三)poll使用流程
        • (四)实例代码

(一)poll轮询的作用

以阻塞的方式打开文件,那么对多个文件读写时,若某个文件未准备好,则系统会处于读写阻塞,并影响其他文件的读写,poll轮训就是实现既可使用输入输出流又不想阻塞在任何一个设备的读写操作
调用poll函数返回时,会返回一个文件是否可读写的标志状态,用户程序根据不同的标志状态来读写相应的文件,实现阻塞方式打开但是非阻塞方式读写的结果

(二)poll轮询相关的接口

  1. 系统层接口:
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd *fds: 轮训描述符的集合数据结构
struct pollfd {int   fd;         /* file descriptor */轮训的文件描述符short events;     /* requested events */对于轮训的文件描述所检测的事件类型short revents;    /* returned events */对于轮训的文件描述所返回的事件类型
};
nfds_t nfds:轮训描述符的个数
int timeout:轮询时间

请求事件和返回事件类型:

POLLIN      There is data to read.
POLLOUT     Writing  is now possible, though a write larger that the available spacein a socket or pipe will still block (unless O_NONBLOCK is set).
POLLPRI:   There is urgent data to read
POLLERR:   Error condition (only returned in revents; ignored in events).POLLHUP:   Hang up (only returned in revents; ignored in events). 
POLLNVAL:  Invalid request: fd not open (only returned in revents; ignored in events).
POLLRDNORM  Equivalent to POLLIN.
POLLRDBAND  Priority band data can be read (generally unused on Linux).POLLWRNOR   Equivalent to POLLOUT.POLLWRBAND  Priority data may be written.
RETURN VALUE On success, a positive number is returned; this is  the  number  of  structures  which  havenonzero  revents  fields (in other words, those descriptors with events or errors reported).A value of 0 indicates that the call timed out and  no  file  descriptors  were  ready.   Onerror, -1 is returned, and errno is set appropriately.
  1. 内核层接口:
unsigned int (*poll) (struct file *, struct poll_table_struct *);//file_operations结构体里

设置轮训的等待队列poll_wait:

static inline void poll_wait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p)
{if (p && p->_qproc && wait_address)p->_qproc(filp, wait_address, p);
}

唤醒等待队列节点wake_up_interruptible或wake_up:

#define wake_up(x)			__wake_up(x, TASK_NORMAL, 1, NULL)
void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr, void *key);
/*** __wake_up - wake up threads blocked on a waitqueue.* @q: the waitqueue* @mode: which threads* @nr_exclusive: how many wake-one or wake-many threads to wake up* @key: is directly passed to the wakeup function** It may be assumed that this function implies a write memory barrier before* changing the task state if and only if any tasks are woken up.*/

(三)poll使用流程

1.内核层编写poll相关的函数

unsigned int cdev_poll (struct file * fp, struct poll_table_struct * table)

2.在合适cdev_poll函数中调用poll_wait

 poll_wait(fp,&waithead,table);//不会进行阻塞,添加等待队列到轮询列表中

3.在合适的地方调用wake_up_interruptible唤醒poll等待队列

wake_up_interruptible(&waithead)

(四)实例代码

假设要求创建多个设备节点,每个设备节点对应一个设备,在系统调用多次read接口来读取底层设备的状态。例如4个按键 ----- 4个设备节点 ----分别读取4个设备节点文件的数据获取按键的状态-----不确定哪一个按键被按下
分析:
若采用阻塞方式操作:四个读写操作会相互阻塞,如按键1未被按下,则读取不到数据,既是按键4被按下,也会被按键1的操作阻塞,获取不到数据
若采用非阻塞操作:既是读取不到数据,也会直接返回,对于监测按键的状态,按键随时可能被按下,所以需要的是循环检测,采用非阻塞就会导致一直在进行无用功
采用多路io轮询操作:检测是文件描述符是否发生变化,变化就去操作对应的文件,否则阻塞在指定的操作
chrdev.c

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/poll.h>#define CDEVCOUNT 5
#define CDEVNAME "cdevdevice"
#define INODENAME "mycdev"
int count=0;
dev_t dev=0;
int keyflag;//等待队列第二个参数
char keyvalue[4]={-1,-1,-1,-1};
struct cdev * cdev =NULL;
struct class * cdevclass =NULL;
wait_queue_head_t  waithead;struct Key
{unsigned int gpios;char * name;int num;unsigned int irq;
};struct Key key[]={{EXYNOS4_GPX3(2),"K1",0},{EXYNOS4_GPX3(3),"K2",1},{EXYNOS4_GPX3(4),"K3",2},{EXYNOS4_GPX3(5),"K4",3},
};irqreturn_t key_handler(int irq, void * dev)
{struct Key * tmp =(struct Key *)dev;int value[4];value[tmp->num]= gpio_get_value(tmp->gpios);gpio_set_value(EXYNOS4X12_GPM4(tmp->num),value[tmp->num]);keyflag = 1;keyvalue[tmp->num] = value[tmp->num];wake_up_interruptible(&waithead);return IRQ_HANDLED;
}int cdev_open (struct inode *node, struct file *file)
{printk("cdev_open is install\n");return 0;
}
ssize_t cdev_read (struct file *fp, char __user *buf, size_t size, loff_t *offset)
{int ret =0;if((fp->f_flags & O_NONBLOCK)== O_NONBLOCK)//非阻塞{if(!keyflag)return -EAGAIN;}else//阻塞{wait_event_interruptible(waithead,keyflag);}keyflag =0;ret = copy_to_user(buf,keyvalue,4);if(ret <0)return -EFAULT;printk("cdev_read is install\n");return 0;
}
ssize_t cdev_write (struct file *fp, const char __user * buf, size_t size, loff_t *offset)
{printk("cdev_write is install\n");return 0;
}
unsigned int cdev_poll (struct file * fp, struct poll_table_struct * table)
{unsigned int bitmask =0;printk("this is poll_wait before\n");poll_wait(fp,&waithead,table);//不会进行阻塞,添加等待队列到轮询列表中if(keyflag)//必须有判断标志bitmask = POLLIN;printk("this is poll_wait after\n");return bitmask;
}int cdev_release (struct inode *node, struct file *fp)
{printk("cdev_release is install\n");return 0;
}
struct file_operations fop={.open=cdev_open,.read=cdev_read,.write=cdev_write,.release=cdev_release,.poll = cdev_poll,
};void mycdev_add(void)
{//1.申请设备号--动态int ret =alloc_chrdev_region(&dev,0, CDEVCOUNT, CDEVNAME);if(ret)return ;//初始化cdev结构体cdev = cdev_alloc();if(!cdev){goto out;}cdev_init(cdev,&fop);//添加字符设备到系统中ret =cdev_add(cdev,dev, CDEVCOUNT);if(ret){goto out1;}//创建设备类cdevclass = class_create(THIS_MODULE, INODENAME);if(IS_ERR(cdevclass)){goto out2;}for (count=0;count<CDEVCOUNT;count++)device_create(cdevclass, NULL, dev+count, NULL, "mydevice%d",count);out:unregister_chrdev_region(dev,CDEVCOUNT);	return ;
out1:unregister_chrdev_region(dev,CDEVCOUNT);kfree(cdev);return ;
out2:cdev_del(cdev);unregister_chrdev_region(dev,CDEVCOUNT);kfree(cdev);return ;
}static int __init  dev_module_init(void)
{int ret=0,i=0;unsigned long flags= IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING|IRQF_SHARED;for(i=0;i<4;i++){key[i].irq = gpio_to_irq(key[i].gpios);ret =request_irq(key[i].irq, key_handler,flags,key[i].name,(void *) &key[i]);}init_waitqueue_head(&waithead);//创建等待队列头mycdev_add();printk("this is dev_module_init \n");return 0;
}static void __exit dev_module_cleanup(void)
{int i=0;for(i=0;i<4;i++){key[i].irq = gpio_to_irq(key[i].gpios);free_irq(key[i].irq,(void *)&key[i]);}for(count=0;count<CDEVCOUNT;count++){device_destroy(cdevclass, dev+count);}class_destroy(cdevclass);cdev_del(cdev);unregister_chrdev_region(dev, CDEVCOUNT);kfree(cdev);printk("this is dev_module_cleanup\n");
}module_init(dev_module_init);
module_exit(dev_module_cleanup);
MODULE_LICENSE("GPL");

chr_app.c

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>int ret=0;
struct pollfd fds[1];
char status[]={-1,-1,-1,-1};
char key[]={-1,-1,-1,-1};
int main(int argc, char *argv[])
{int i=0,fd= open(argv[1],O_RDWR/*|O_NONBLOCK*/);if(fd== -1){perror("open");return -1;}while(1){fds[0].fd = fd;fds[0].events = POLLIN;ret = poll(fds,1,5000);//只有错误、满足条件、超时才会返回,不满足条件在这死等if(ret == -1){perror("poll\n");return -1;}else if(ret == 0){printf("timeout\n");}else if(ret & POLLIN){printf("ret >0\n");if(read(fd,status,4)<0)/*疑问:把read屏蔽掉打印出错*/{printf("按键状态未改变\n");sleep(1);continue;}for(i=0;i<4;i++){if(status[i] != key[i] ){printf("key%d is %s\n",i,status[i]?"up":"down");status[i]=key[i];}}}}close(fd);return 0;
}

Makefile

CFLAG =-C
TARGET = chrdev
TARGET1 = chr_app
KERNEL = /mydriver/linux-3.5
obj-m += $(TARGET).oall:make $(CFLAG)  $(KERNEL) M=$(PWD)arm-linux-gcc -o $(TARGET1) $(TARGET1).c
clean:make $(CFLAG)  $(KERNEL) M=$(PWD) clean

本文章仅供学习交流用禁止用作商业用途,文中内容来水枂编辑,如需转载请告知,谢谢合作

微信公众号:zhjj0729

微博:文艺to青年

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531409.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

校验码(海明校验,CRC冗余校验,奇偶校验)

循环冗余校验码 CRC码利用生成多项式为k个数据位产生r个校验位进行编码,其编码长度为nkr所以又称 (n,k)码. CRC码广泛应用于数据通信领域和磁介质存储系统中. CRC理论非常复杂,一般书就给个例题,讲讲方法.现在简单介绍下它的原理: 在k位信息码后接r位校验码,对于一个给定的(n,k…

(十二)linux内核定时器

目录&#xff08;一&#xff09;内核定时器介绍&#xff08;二&#xff09;内核定时器相关接口&#xff08;三&#xff09;使用步骤&#xff08;四&#xff09;实例代码&#xff08;一&#xff09;内核定时器介绍 内核定时器并不是用来简单的定时操作&#xff0c;而是在定时时…

java Proxy(代理机制)

我们知道Spring主要有两大思想&#xff0c;一个是IoC&#xff0c;另一个就是AOP&#xff0c;对于IoC&#xff0c;依赖注入就不用多说了&#xff0c;而对于Spring的核心AOP来说&#xff0c;我们不但要知道怎么通过AOP来满足的我们的功能&#xff0c;我们更需要学习的是其底层是怎…

(十三)linux中断底半部分处理机制

这篇文章介绍一下linux中断的底半部分的tasklet和workquene两种处理机制&#xff0c;其中tasklet中不能有延时函数&#xff0c;workquene的处理函数可以加入延时操作 目录&#xff08;一&#xff09;tasklet小任务处理机制&#xff08;1&#xff09;tasklet相关函数接口&#x…

Codeforces Round #326 (Div. 2) B. Pasha and Phone C. Duff and Weight Lifting

B. Pasha and PhonePasha has recently bought a new phone jPager and started adding his friends phone numbers there. Each phone number consists of exactly n digits. Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, …

vmware中装的ubuntu上不了网

本文章针对桥接方式进行讲解&#xff0c;如果需要另外两种连接方式请参考文末给出的链接 &#xff08;一&#xff09;问题 主机和虚拟机可以相互ping通&#xff0c;但是却不能ping网址 &#xff08;二&#xff09;解决办法 vmware为我们提供了三种网络工作模式&#xff0c;…

document.getElementById()与 $()区别

document.getElementById()返回的是DOM对象&#xff0c;而$()返回的是jQuery对象 什么是jQuery对象&#xff1f; ---就是通过jQuery包装DOM对象后产生的对象。jQuery对象是jQuery独有的&#xff0c;其可以使用jQuery里的方法。 比如&#xff1a; $("#test").html() 意…

关于gedit的编码问题

今天由于gedit的编码格式导致LCD显示屏的问题&#xff0c;开始没有想到后来才发现&#xff0c;在这记录一下 #include <stdio.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <linux/fb.h> #include <sys/mman.h>…

c语言表白程序代码

双十一要到了&#xff0c;好激动啊&#xff01;&#xff01;&#xff01; 是时候准备出手了&#xff01; 花了一天的时间写的表白代码。 表示自己弱弱的..... 看了网上好多都是js写的&#xff0c;感觉碉堡了&#xff01;js用的不熟&#xff0c;前端不好&#xff0c;java&#x…

tiny4412移植tslib库

1、将tslib-1.4.tar.gz拷贝到虚拟机某个路径进行解压 2、进入解压路径tslib 3、执行#./autogen.sh 如果提示&#xff1a;./autogen.sh: 4: ./autogen.sh: autoreconf: not found 原因&#xff1a;没有安装automake工具, 解决办法:需要安装此工具&#xff1a; apt-get instal…

移植QT到tiny4412开发板

目录&#xff08;一&#xff09; 环境准备&#xff08;二&#xff09; Qt源代码下载&#xff08;三&#xff09; 移植tslib库&#xff08;四&#xff09;操作流程1.解压qt源码包2.配置编译环境3.生成Makefile4.编译安装5.安装一些库用来支持 qt6. 添加以下内容到开发板目录下的…

c++面试常用知识(sizeof计算类的大小,虚拟继承,重载,隐藏,覆盖)

一. sizeof计算结构体 注&#xff1a;本机机器字长为64位 1.最普通的类和普通的继承 #include<iostream> using namespace std;class Parent{ public:void fun(){cout<<"Parent fun"<<endl;} }; class Child : public Parent{ public:void fun(){…

嵌入式面试题(一)

目录1 关键字volatile有什么含义&#xff1f;并给出三个不同的例子2. c和c中的struct有什么不同&#xff1f;3.进程和线程区别4.ARM流水线5.使用断言6 .嵌入式系统的定义7 局部变量能否和全局变量重名&#xff1f;8 如何引用一个已经定义过的全局变量&#xff1f;9、全局变量可…

能ping通ip但无法ping通域名和localhost //ping: bad address 'www.baidu.com'

错误描述&#xff1a; ~ # ping localhost ping: bad address localhost原因&#xff0c;在/etc目录下缺少hosts文件&#xff0c;将linux中的/etc hosts文件拷入即可 ~ # ping localhost PING localhost (127.0.0.1): 56 data bytes 64 bytes from 127.0.0.1: seq0 ttl64 tim…

eclipse导入web项目之后项目中出现小红叉解决办法

项目中有小红叉我遇到的最常见的情况&#xff1a; 1、项目代码本身有问题。&#xff08;这个就不说了&#xff0c;解决错误就OK&#xff09; 2、项目中的jar包丢失。&#xff08;有时候eclipse打开时会出现jar包丢失的情况&#xff0c;关闭eclipse重新打开或者重新引入jar包就O…

arm开发板通过网线连接笔记本电脑上外网

需要工具&#xff1a;arm开发板&#xff0c;网线&#xff0c;一台双网卡的win7笔记本电脑&#xff08;笔记本电脑一般都是双网卡&#xff09; 一、笔记本电脑需要先连上外网&#xff0c;可以连上家里的WIFI&#xff0c;或者手机开热点&#xff08;本人未测试过连接手机的热点&…

windows下实现Git在局域网使用

1.首先在主机A上创建一个文件夹用于存放你要公开的版本库。然后进入这个文件夹&#xff0c;右键->Git create repository here&#xff0c;弹出的窗口中勾选Make it Bare&#xff01;之后将这个文件夹完全共享&#xff08;共享都会吧&#xff1f;注意权限要让使用这个文件夹…

解决linux下QtCreator无法输入中文的情况

安装了QtCreator(Qt5.3.1自带版本)后无法输入中文&#xff0c;确切的说是无法打开输入法。以前使用iBus输入法的时候没有这个问题&#xff0c;现在使用sougou输入法才有的这个问题。 可以查看此文 http://www.cnblogs.com/oloroso/p/5114041.html 原因 有问题就得找原因&…

lintcode 滑动窗口的最大值(双端队列)

题目链接&#xff1a;http://www.lintcode.com/zh-cn/problem/sliding-window-maximum/# 滑动窗口的最大值 给出一个可能包含重复的整数数组&#xff0c;和一个大小为 k 的滑动窗口, 从左到右在数组中滑动这个窗口&#xff0c;找到数组中每个窗口内的最大值。 样例 给出数组 [1…

你的main函数规范吗?

在学习c语言的时候&#xff0c;有一个函数一直被我们使用&#xff0c;那就是main函数&#xff0c;但是你知道标准里面是怎么规定它的写法吗&#xff1f; 平时看见的main函数有下面这几种&#xff1a; 1.int main(void){ }2.int main(){ }3.int main(int argc, char *argv[])…