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原理:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM