驱动练习 部分poll函数+应用层代码

unsigned int mycdev_poll(struct file *file,struct poll_table_stru    ct *wait)
 {
         unsigned int mask;
         poll_wait(file,&wq,wait);
         if(condition)
                 mask |= POLLIN;
                 return mask;
 }
———————————————————————————————————————————

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
char buf[128] = {0};

int main(int argc, const char *argv[])
{
        int fd1,fd2,i;
        int ret;
        fd_set rfds;
        fd1=open("/dev/mycdev0",O_RDWR);
        if(fd1==-1)
        {
                perror("mycdev0 open err");
                return -1; 
        }
        fd2=open("/dev/hello0",O_RDWR);
        if(fd2==-1)
        {
                perror("hello0 open err");
                return -1; 
        }
        while(1)
        {
                FD_ZERO(&rfds);
                FD_SET(fd1,&rfds);    
                FD_SET(fd2,&rfds);          
                ret=select(fd2+1,&rfds,NULL,NULL,NULL);
                if(ret==-1)
                {
                        perror("select fail");
                        return -1; 
                }   
for(i=3;i<fd2+1;i++)
{
                if(FD_ISSET(i,&rfds))   
                {
                        memset(buf,0,sizeof(buf));
                        read(i,buf,sizeof(buf));
                        printf("fd%d = %s",i,buf);
                }
}    
}
        close(fd1);
        close(fd2);

        return 0;
}
 

应用层中,`poll()`函数是用于监视多个文件描述符的函数,并等待其中的一个或多个文件描述符上发生事件。它的原型如下: ```c #include <poll.h> int poll(struct pollfd *fds, nfds_t nfds, int timeout); ``` 其中,参数说明如下: - `fds`:一个指向`struct pollfd`结构体数组的指针,每个结构体描述一个文件描述符以及该文件描述符上感兴趣的事件。 - `nfds`:`fds`数组中元素的个数。 - `timeout`:等待的超时时间,以毫秒为单位。传递负值表示无限等待,传递0表示立即返回。 `struct pollfd`结构体定义如下: ```c struct pollfd { int fd; // 文件描述符 short events; // 需要监视的事件(可使用POLLIN、POLLOUT等常量组合) short revents; // 实际发生的事件(由内核填充) }; ``` `events`字段用于指定需要监视的事件,可以使用以下常量进行组合: - `POLLIN`:可读事件 - `POLLOUT`:可写事件 - `POLLERR`:错误事件 - `POLLHUP`:挂起事件 - `POLLNVAL`:无效事件 `revents`字段由内核在返回时填充,表示实际发生的事件。 `poll()`函数的返回值表示发生事件的文件描述符数量,返回值为负数表示出错,0表示超时,正数表示发生事件的文件描述符数量。 注意,在使用`poll()`函数前,需要包含头文件`<poll.h>`。另外,还可以使用`pselect()`函数和`ppoll()`函数来替代`poll()`函数,它们在一些特定的场景下提供了更多的功能和选项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值