相信自己,只有不想做的,没有做不到的。
分类: LINUX
2013-12-12 13:01:21
poll//8 poll的使用
/定义
.poll = globalfifo_poll,
//结构体
/*globalfifo设备结构体*/
struct globalfifo_dev
{
struct cdev cdev; /*cdev结构体*/
unsigned int current_len; /*fifo有效数据长度*/
unsigned char mem[GLOBALFIFO_SIZE]; /*全局内存*/
struct semaphore sem; /*并发控制用的信号量*/
wait_queue_head_t r_wait; /*阻塞读用的等待队列头*/
wait_queue_head_t w_wait; /*阻塞写用的等待队列头*/
};
//函数调用
static unsigned int globalfifo_poll(struct file *filp, poll_table *wait)
{
unsigned int mask = 0;
struct globalfifo_dev *dev = filp->private_data; /*获得设备结构体指针*/
down(&dev->sem);
poll_wait(filp, &dev->r_wait, wait);
poll_wait(filp, &dev->w_wait, wait);
/*fifo非空*/
if (dev->current_len != 0)
{
mask |= POLLIN | POLLRDNORM; /*标示数据可获得*/
}
/*fifo非满*/
if (dev->current_len != GLOBALFIFO_SIZE)
{
mask |= POLLOUT | POLLWRNORM; /*标示数据可写入*/
}
up(&dev->sem);
return mask;
}
poll应用程序编写
int main()
{
int fd, num;
char rd_ch[BUFFER_LEN];
fd_set rfds,wfds;
/*以非阻塞方式打开/dev/globalmem设备文件*/
fd = open("/dev/globalfifo", O_RDONLY | O_NONBLOCK);
if (fd != - 1)
{
/*FIFO清0*/
if (ioctl(fd, FIFO_CLEAR, 0) < 0)
{
printf("ioctl command failed\n");
}
while (1)
{
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_SET(fd, &rfds);
FD_SET(fd, &wfds);
select(fd + 1, &rfds, &wfds, NULL, NULL);
/*数据可获得*/
if (FD_ISSET(fd, &rfds))
{
printf("Poll monitor:can be read\n");
}
/*数据可写入*/
if (FD_ISSET(fd, &wfds))
{
printf("Poll monitor:can be written\n");
}
sleep(1);
}
}
else
{
printf("Device open failure\n");
}
}