Linux之poll与select20160619

使用非阻塞I/O的应用程序通常会使用select()poll()系统调用查询是否可对设备进行无阻塞的访问,这两个系统调用最终又会引发设备驱动中的poll()函数被执行

 

如果当前不可读(先调用驱动.poll确定是否可读,然后继续do_poll),那么在sys_poll->do_poll中当前进程就会睡眠在等待队列上,这个等待队列是由驱动程序提供的(就是poll_wait中传入的那个)。当可读的时候,驱动程序可能有一部分代码运行了(比如驱动的中断服务

程序),那么在这部分代码中,就会唤醒等待队列上的进程,也就是之前睡眠的那个,当那个进程被唤醒后do_poll会再一次的调用驱动程序的poll函数,这个时候应用程序就知道是可读的了。

 

首先,先说说Poll函数的使用,原理部分见文章最后的附图,我们直接看程序代码示例比较直观:

1.应用程序:

#include <fcntl.h>

#include <stdio.h>

#include <poll.h>

 

 

/* forthdrvtest

  */

int main(int argc, char **argv)

{

int fd;

unsigned char key_val;

int ret;

 

struct pollfd fds[1];

 

fd = open("/dev/buttons", O_RDWR);

if (fd < 0)

{

printf("can't open!\n");

}

 

fds[0].fd     = fd;

fds[0].events = POLLIN;//期待获取的值是有数据等待读取

while (1)

{

ret = poll(fds, 1, 5000);//查询一个文件fds

if (ret == 0)

{

printf("time out\n");

}

else

{

read(fd, &key_val, 1);

printf("key_val = 0x%x\n", key_val);

}

}

 

return 0;

2.驱动程序:

#include <linux/module.h>

#include <linux/kernel.h>

#include <linux/fs.h>

#include <linux/init.h>

#include <linux/delay.h>

#include <linux/irq.h>

#include <asm/uaccess.h>

#include <asm/irq.h>

#include <asm/io.h>

#include <asm/arch/regs-gpio.h>

#include <asm/hardware.h>

#include <linux/poll.h>

 

 

static struct class *forthdrv_class;

static struct class_device *forthdrv_class_dev;

 

volatile unsigned long *gpfcon;

volatile unsigned long *gpfdat;

 

volatile unsigned long *gpgcon;

volatile unsigned long *gpgdat;

 

 

static DECLARE_WAIT_QUEUE_HEAD(button_waitq);

 

/* 中断事件标志, 中断服务程序将它置1forth_drv_read将它清0 */

static volatile int ev_press = 0;

 

 

struct pin_desc{

unsigned int pin;

unsigned int key_val;

};

 

 

/* 键值: 按下时, 0x01, 0x02, 0x03, 0x04 */

/* 键值: 松开时, 0x81, 0x82, 0x83, 0x84 */

static unsigned char key_val;

 

struct pin_desc pins_desc[4] = {

{S3C2410_GPF0, 0x01},

{S3C2410_GPF2, 0x02},

{S3C2410_GPG3, 0x03},

{S3C2410_GPG11, 0x04},

};

 

 

/*

  * 确定按键值

  */

static irqreturn_t buttons_irq(int irq, void *dev_id)

{

struct pin_desc * pindesc = (struct pin_desc *)dev_id;

unsigned int pinval;

 

pinval = s3c2410_gpio_getpin(pindesc->pin);

 

if (pinval)

{

/* 松开 */

key_val = 0x80 | pindesc->key_val;

}

else

{

/* 按下 */

key_val = pindesc->key_val;

}

 

    ev_press = 1;                  /* 表示中断发生了 */

    wake_up_interruptible(&button_waitq);   /* 唤醒休眠的进程 */

 

 

return IRQ_RETVAL(IRQ_HANDLED);

}

 

static int forth_drv_open(struct inode *inode, struct file *file)

{

/* 配置GPF0,2为输入引脚 */

/* 配置GPG3,11为输入引脚 */

request_irq(IRQ_EINT0,  buttons_irq, IRQT_BOTHEDGE, "S2", &pins_desc[0]);

request_irq(IRQ_EINT2,  buttons_irq, IRQT_BOTHEDGE, "S3", &pins_desc[1]);

request_irq(IRQ_EINT11, buttons_irq, IRQT_BOTHEDGE, "S4", &pins_desc[2]);

request_irq(IRQ_EINT19, buttons_irq, IRQT_BOTHEDGE, "S5", &pins_desc[3]);

 

return 0;

}

 

ssize_t forth_drv_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)

{

if (size != 1)

return -EINVAL;

 

/* 如果没有按键动作, 休眠 */

wait_event_interruptible(button_waitq, ev_press);

 

/* 如果有按键动作, 返回键值 */

copy_to_user(buf, &key_val, 1);

ev_press = 0;

 

return 1;

}

 

 

int forth_drv_close(struct inode *inode, struct file *file)

{

free_irq(IRQ_EINT0, &pins_desc[0]);

free_irq(IRQ_EINT2, &pins_desc[1]);

free_irq(IRQ_EINT11, &pins_desc[2]);

free_irq(IRQ_EINT19, &pins_desc[3]);

return 0;

}

 

static unsigned forth_drv_poll(struct file *file, poll_table *wait)

{

unsigned int mask = 0;

poll_wait(file, &button_waitq, wait); // 不会立即休眠

 

if (ev_press)

mask |= POLLIN | POLLRDNORM;//自己查找分析?

 

return mask;

}

 

 

 

static struct file_operations sencod_drv_fops = {

    .owner   =  THIS_MODULE,    /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */

    .open    =  forth_drv_open,     

.read  = forth_drv_read,    

.release =  forth_drv_close,

.poll    =  forth_drv_poll,

};

 

 

int major;

static int forth_drv_init(void)

{

major = register_chrdev(0, "forth_drv", &sencod_drv_fops);

 

forthdrv_class = class_create(THIS_MODULE, "forth_drv");

 

forthdrv_class_dev = class_device_create(forthdrv_class, NULL, MKDEV(major, 0), NULL, "buttons"); /* /dev/buttons */

 

gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16);

gpfdat = gpfcon + 1;

 

gpgcon = (volatile unsigned long *)ioremap(0x56000060, 16);

gpgdat = gpgcon + 1;

 

return 0;

}

 

static void forth_drv_exit(void)

{

unregister_chrdev(major, "forth_drv");

class_device_unregister(forthdrv_class_dev);

class_destroy(forthdrv_class);

iounmap(gpfcon);

iounmap(gpgcon);

return 0;

}

 

 

module_init(forth_drv_init);

 

module_exit(forth_drv_exit);

 

MODULE_LICENSE("GPL");

其次,我们看一下实际使用的比较多的Select函数:

 

select()函数、

同样select中,Poll方法只是做一个登记,真正的阻塞发生在select.c 中的 do_select函数。

原型如下:

int select(int fdsp1, fd_set *readfds, fd_set *writefds, fd_set *errorfds, const struct timeval *timeout);

各个参数含义如下:

int fdsp1:最大描述符值 + 1

fd_set *readfds:对可读感兴趣的描述符集

fd_set *writefds:对可写感兴趣的描述符集

fd_set *errorfds:对出错感兴趣的描述符集

struct timeval *timeout:超时时间

select函数会在发生以下情况时返回:

1 readfds集合中有描述符可读

2 writefds集合中有描述符可写

3 errorfds集合中有描述符遇到错误条件

4 指定的超时时间timeout到了

3Select系统调用(返回值)

      Select调用返回时,返回值有如下情况:

      1)正常情况下返回满足要求的文件描述符个数;

      2)经过了timeout等待后仍无文件满足要求,返回值为0;

      3)如果select被某个信号中断,它将返回-1并设置errnoEINTR

      4)如果出错,返回-1并设置相应的errno

4Select系统调用(使用方法)

      1)将要监控的文件添加到文件描述符集

      2)调用Select开始监控

      3)判断文件是否发生变化

        系统提供了4个宏对描述符集进行操作:

        #include <sys/select.h>

        void FD_SET(int fd, fd_set *fdset)

        void FD_CLR(int fd, fd_set *fdset)

        void FD_ZERO(fd_set *fdset)

        void FD_ISSET(int fd, fd_set *fdset)

        宏FD_SET将文件描述符fd添加到文件描述符集fdset;

        宏FD_CLR从文件描述符集fdset中清除文件描述符fd;

        宏FD_ZERO清空文件描述符集fdset;

        在调用select后使用FD_ISSET来检测文件描述符集fdset中的文件fd发生了变化。

     FD_ZERO(&fds); //清空集合

     FD_SET(fd1,&fds); //设置描述符

     FD_SET(fd2,&fds); //设置描述符

       maxfdp=fd1+1; //描述符最大值加1,假设fd1>fd2

       switch(select(maxfdp,&fds,NULL,NULL,&timeout))

             case -1: exit(-1);break; //select错误,退出程序

             case 0:break;

             default:

       if(FD_ISSET(fd1,&fds)) //测试fd1是否可读

 

 

 

unsigned int (*poll)(struct file *filp, struct poll_table *wait);

这个函数要进行下面两项工作。首先,对可能引起设备文件状态变化的等待队列调用poll_wait(),将对应的等待队列头添加到poll_table.

 

然后,返回表示是否能对设备进行无阻塞读写访问的掩码。在上面提到了一个poll_wait()函数,它的原型:

void poll_wait(struct file *filp, wait_queue_head_t *queue, poll_table *wait);

它的作用就是把当前进程添加到wait参数指定的等待列表(poll_table)中。需要注意的是这个函数是不会引起阻塞的,呵呵,谁给它取得个

 

名字带wait的,给咱们添这么多麻烦。

static unsigned int mem_poll(struct file *filp,poll_table *wait)

{

 

struct scull_pipe *dev =filp->private_data;

unsigned int mask =0;

/* 把等待队列添加到poll_table */

poll_wait(filp,&dev->inq,wait);

/*返回掩码*/

if (有数据可读)

mask = POLLIN |POLLRDNORM;/*设备可读*/

return mask;

 

}

例:

int main()

{

    int fd;

    fd_set rds;    //声明描述符集合

    int ret;

    char Buf[128];

     

    /*初始化Buf*/

    strcpy(Buf,"memdev is char dev!");

    printf("BUF: %s\n",Buf);

     

    /*打开设备文件*/

    fd = open("/dev/memdev0",O_RDWR);

    

    FD_ZERO(&rds);   //清空描述符集合

    FD_SET(fd, &rds); //设置描述符集合

 

    /*清除Buf*/

    strcpy(Buf,"Buf is NULL!");

    printf("Read BUF1: %s\n",Buf);

 

    ret = select(fd + 1, &rds, NULL, NULL, NULL);//调用select()监控函数

    if (ret < 0)  

    {

        printf("select error!\n");

        exit(1);

    }

    if (FD_ISSET(fd, &rds))   //测试fd1是否可读  

        read(fd, Buf, sizeof(Buf));             

     

    /*检测结果*/

    printf("Read BUF2: %s\n",Buf);

    

    close(fd);

     

    return 0;     

}

1select的第一个参数nfdsfdset集合中最大描述符值加1fdset是一个位数组,其大小限制为__FD_SETSIZE1024),位数组的每一位

 

代表其对应的描述符是否需要被检查。

select的第二三四个参数表示需要关注读、写、错误事件的文件描述符位数组,这些参数既是输入参数也是输出参数,可能会被内核修改用

 

于标示哪些描述符上发生了关注的事件。所以每次调用select前都需要重新初始化fdset

timeout参数为超时时间,该结构会被内核修改,其值为超时剩余的时间。

 

select对应于内核中的sys_select调用,sys_select首先将第二三四个参数指向的fd_set拷贝到内核,然后对每个被SET的描述符调用进行

 

poll,并记录在临时结果中(fdset),如果有事件发生,select会将临时结果写到用户空间并返回;当轮询一遍后没有任何事件发生时,

 

如果指定了超时时间,则select会睡眠到超时,睡眠结束后再进行一次轮询,并将临时结果写到用户空间,然后返回。

select返回后,需要逐一检查关注的描述符是否被SET(事件是否发生)。

 

Select原理:

select系统调用的代码在fs/Select.c下,

前面是从用户控件拷贝各个fd_set到内核空间,接下来的具体工作在core_sys_select中,

core_sys_select->do_select,真正的核心内容在do_select里:

mask = (*f_op->poll)(file, retval ? NULL : wait);

这个是调用文件系统的 poll函数,不同的文件系统poll函数自然不同,由于我们这里关注的是tcp连接,而

 

socketfs的注册在 net/Socket.c里。register_filesystem(&sock_fs_type); socket文件系统的函数也是在

 

net/Socket.c里:

sock_poll跟随下去,

最后可以到 net/ipv4/tcp.c

unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)

这个是最终的查询函数,

也就是说select 的核心功能是调用tcp文件系统的poll函数,不停的查询,如果没有想要的数据,主动执行一次调度(防止一直占用cpu

 

,直到有一个连接有想要的消息为止。

从这里可以看出select的执行方式基本就是不同的调用poll,直到有需要的消息为止,如果select 处理的socket很多,这其实对整个机器的性能也是一个消耗。

 

 

很简单吧,最后附笔者的笔记:

 

Poll原理:

 

posted @ 2016-06-19 15:01  yuweifeng  阅读(1901)  评论(0编辑  收藏  举报