Linux驱动开发--五种IO模型

本文详细介绍了Linux内核中的五种IO模型:阻塞、非阻塞、多路复用(select、poll、epoll)、信号驱动以及它们在应用层和驱动层的实现。通过示例代码展示了如何在驱动程序中处理这些IO模型,并提供了应用层的使用示例。
摘要由CSDN通过智能技术生成

一、五种IO模型------读写外设数据的方式

1.阻塞: 不能操作就睡觉

2.非阻塞:不能操作就返回错误

3.多路复用:委托中介监控

4.信号驱动:让内核如果能操作时发信号,在信号处理函数中操作

5.异步IO:向内核注册操作请求,内核完成操作后发通知信号

 二、阻塞与非阻塞

应用层:

​ open时由O_NONBLOCK指示read、write时是否阻塞

​ open以后可以由fcntl函数来改变是否阻塞:

flags = fcntl(fd,F_GETFL,0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);

驱动层:通过等待队列

wait_queue_head_t //等待队列头数据类型

init_waitqueue_head(wait_queue_head_t *pwq) //初始化等待队列头
    
wait_event_interruptible(wq,condition)
/*
功能:条件不成立则让任务进入浅度睡眠,直到条件成立醒来
    wq:等待队列头
    condition:C语言表达式
返回:正常唤醒返回0,信号唤醒返回非0(此时读写操作函数应返回-ERESTARTSYS)
*/
        
wait_event(wq,condition) //深度睡眠

wake_up_interruptible(wait_queue_head_t *pwq)
        
wake_up(wait_queue_head_t *pwq)
    
    
/*
1. 读、写用不同的等待队列头rq、wq
2. 无数据可读、可写时调用wait_event_interruptible(rq、wq,条件)
3. 写入数据成功时唤醒rq,读出数据成功唤醒wq
*/

就绪态有一个链式队列,队列中有很多节点

当一个cpu时间片开始时取出队列中的头节点去运行一个时间片然后插入到队尾

睡眠态怎么实现呢,再搞一个队列叫等待队列。把一个任务放到等待队列就处于睡眠态了。把任务从等待队列放到就绪队列就会继续参与时间片轮转。

睡眠分两种,资源就位了,满足的条件成立了才会醒来的叫深度睡眠,除了这俩情况接收到信号也会醒来的叫浅睡眠)

代码示例

mychar.h

#ifndef MY_CHAR_H
#define MY_CHAR_H
 
#include <asm/ioctl.h>
 
#define MY_CHAR_MAGIC 'k'
 
#define MYCHAR_IOCTL_GET_MAXLEN _IOR(MY_CHAR_MAGIC,1,int*)
#define MYCHAR_IOCTL_GET_CURLEN _IOR(MY_CHAR_MAGIC,2,int*)
 
 
#endif

mychar.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#include <linux/wait.h>
#include <linux/sched.h>
 
 
#include "mychar.h"
 
#define BUF_LEN 100
 
#define MYCHAR_DEV_CNT 3
 
int major = 11;
int minor = 0;
int mychar_num  = MYCHAR_DEV_CNT;
 
struct mychar_dev
{
    struct cdev mydev;
 
    char mydev_buf[BUF_LEN];
    int curlen;
    wait_queue_head_t rq;
    wait_queue_head_t wq;
     
};
 
struct mychar_dev gmydev;
 
int mychar_open(struct inode *pnode,struct file *pfile)
{
    pfile->private_data =(void *) (container_of(pnode->i_cdev,struct mychar_dev,mydev));
    printk("mychar_open is called\n");
    return 0;
}
 
int mychar_close(struct inode *pnode,struct file *pfile)
{
 
    printk("mychar_close is called\n");
    return 0;
}
 
ssize_t mychar_read(struct file *pfile,char __user *puser,size_t count,loff_t *p_pos)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
    int size = 0;
    int ret = 0;
 
    if(pmydev->curlen <= 0)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {//非阻塞
            printk("O_NONBLOCK No Data Read\n");
            return -1;
        }
        else
        {//阻塞
            ret = wait_event_interruptible(pmydev->rq,pmydev->curlen > 0);
            if(ret)
            {
                printk("Wake up by signal\n");
                return -ERESTARTSYS;
            }
        }
    }
 
    if(count > pmydev->curlen)
    {
        size = pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_to_user(puser,pmydev->mydev_buf,size);
    if(ret)
    {
        printk("copy_to_user failed\n");
        return -1;
    }
 
    memcpy(pmydev->mydev_buf,pmydev->mydev_buf + size,pmydev->curlen - size);
 
    pmydev->curlen -= size;
 
    wake_up_interruptible(&pmydev->wq);
         
    return size;
}
 
ssize_t mychar_write(struct file *pfile,const char __user *puser,size_t count,loff_t *p_pos)
{
    int size = 0;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    if(pmydev->curlen >= BUF_LEN)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {
            printk("O_NONBLOCK Can not write data\n");
            return -1;
        }
        else
        {
            ret = wait_event_interruptible(pmydev->wq,pmydev->curlen < BUF_LEN);
            if(ret)
            {
                printk("wake up by signal\n");
                return -ERESTARTSYS;
            }
        }
    }
 
 
    if(count > BUF_LEN-pmydev->curlen)
    {
        size = BUF_LEN - pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_from_user(pmydev->mydev_buf + pmydev->curlen,puser,size);
    if(ret)
    {
        printk("copy_from_user failed\n");
        return -1;
    }
    pmydev->curlen  +=  size;
 
    wake_up_interruptible(&pmydev->rq);
 
    return size;
}
 
long mychar_ioctl(struct file *pfile,unsigned int cmd,unsigned long arg)
{
    int __user *pret = (int *)arg;
    int maxlen = BUF_LEN;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    switch(cmd)
    {
        case MYCHAR_IOCTL_GET_MAXLEN:
            ret = copy_to_user(pret,&maxlen,sizeof(int));
            if(ret)
            {
                printk("copy_to_user MAXLEN failed\n");
                return -1;
            }
            break;
        case MYCHAR_IOCTL_GET_CURLEN:
            ret = copy_to_user(pret,&pmydev->curlen,sizeof(int));
            if(ret)
            {
                printk("copy_to_user CURLEN failed\n");
                return -1;
            }
            break;
        default:
            printk("The cmd is unknow\n");
            return -1;
 
    }
 
    return 0;
}
 
struct file_operations myops = {
    .owner = THIS_MODULE,
    .open = mychar_open,
    .release = mychar_close,
    .read = mychar_read,
    .write = mychar_write,
    .unlocked_ioctl = mychar_ioctl,
};
 
int __init mychar_init(void)
{
    int ret = 0;
    dev_t devno = MKDEV(major,minor);
    int i = 0;
 
    /*申请设备号*/
    ret = register_chrdev_region(devno,mychar_num,"mychar");
    if(ret)
    {
        ret = alloc_chrdev_region(&devno,minor,mychar_num,"mychar");
        if(ret)
        {
            printk("get devno failed\n");
            return -1;
        }
        major = MAJOR(devno);//容易遗漏,注意
    }
 
 
        /*给struct cdev对象指定操作函数集*/  
        cdev_init(&gmydev.mydev,&myops);
 
        /*将struct cdev对象添加到内核对应的数据结构里*/
        gmydev.mydev.owner = THIS_MODULE;
        cdev_add(&gmydev.mydev,devno,1);
 
    init_waitqueue_head(&gmydev->rq);
    init_waitqueue_head(&gmydev->wq);
 
    return 0;
}
 
void __exit mychar_exit(void)
{
    dev_t devno = MKDEV(major,minor);
    int i = 0;
 
    cdev_del(&gmydev_arr[i].mydev);
     
 
    unregister_chrdev_region(devno,mychar_num);
}
 
 
MODULE_LICENSE("GPL");
 
module_init(mychar_init);
module_exit(mychar_exit);

应用层:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
 
#include <stdio.h>
 
#include "mychar.h"
int main(int argc,char *argv[])
{
    int fd = -1;
    char buf[8] = "";
    int ret = 0;
 
    if(argc < 2)
    {
        printf("The argument is too few\n");
        return 1;
    }
 
    fd = open(argv[1],O_RDWR | O_NONBLOCK);
    if(fd < 0)
    {
        printf("open %s failed\n",argv[1]);
        return 2;
    }
 
    ret = read(fd,buf,8);
    if(ret < 0)
    {
        printf("read data failed\n");
    }
    else
    {
        printf("buf=%s\n",buf);
    }
 
    close(fd);
    fd = -1;
    return 0;
}

三、多路复用

描述符:

  1. 文件描述符:设备文件、管道文件
  2. socket描述符

3.1 应用层:三套接口select、poll、epoll

select:位运算实现 监控的描述符数量有限(32位机1024,64位机2048) 效率差

poll:链表实现,监控的描述符数量不限 效率差

epoll:效率最高,监控的描述符数量不限

select

int select(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout);
/*	功能:监听多个描述符,阻塞等待有一个或者多个文件描述符,准备就绪。
		内核将没有准备就绪的文件描述符,从集合中清掉了。
	参数:  nfds			最大文件描述符数 ,加1
			readfds		读文件描述符集合
			writefds		写文件描述符集合
			exceptfds		其他异常的文件描述符集合
			timeout		超时时间(NULL)
	返回值:当timeout为NULL时返回0,成功:准备好的文件描述的个数  出错:-1 
		   当timeout不为NULL时,如超时设置为0,则select为非阻塞,超时设置 > 0,则无描述符可被操作的情况下阻塞指定长度的时间 
*/
void FD_CLR(int fd, fd_set *set);
//功能:将fd 从集合中清除掉

int  FD_ISSET(int fd, fd_set *set);
//功能:判断fd 是否存在于集合中
 
void FD_SET(int fd, fd_set *set);
//功能:将fd 添加到集合中

void FD_ZERO(fd_set *set);
//功能:将集合清零

//使用模型:

while(1)
{
    /*得到最大的描述符maxfd*/
    /*FD_ZERO清空描述符集合*/
	/*将被监控描述符加到相应集合rfds里  FD_SET*/
    /*设置超时*/
    ret = select(maxfd+1,&rfds,&wfds,NULL,NULL);
    if(ret < 0)
    {
        if(errno == EINTR)//错误时信号引起的
        {
        	continue;   
        }
        else
        {
            break;
        }
    }
    else if(ret == 0)
    {//超时
        //.....
    }
    else
    { //> 0 ret为可被操作的描述符个数
        if(FD_ISSET(fd1,&rfds))
        {//读数据
            //....
        }
        if(FD_ISSET(fd2,&rfds))
        {//读数据
            //....
        }
        ///.....
        if(FD_ISSET(fd1,&wfds))
        {//写数据
            //....
        }
    }
}
   

3.2 驱动层:实现poll函数

void poll_wait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p);
/*功能:将等待队列头添加至poll_table表中
  参数:struct file :设备文件
  Wait_queue_head_t :等待队列头
  Poll_table :poll_table表
*/

/*该函数与select、poll、epoll_wait函数相对应,协助这些多路监控函数判断本设备是否有数据可读写*/
unsigned int xxx_poll(struct file *filp, poll_table *wait) //函数名初始化给struct file_operations的成员.poll
{
    unsigned int mask = 0;
    /*
    	1. 将所有等待队列头加入poll_table表中
    	2. 判断是否可读,如可读则mask |= POLLIN | POLLRDNORM;
    	3. 判断是否可写,如可写则mask |= POLLOUT | POLLWRNORM;
    */
    
    return mask;
}

1.3代码示例

mychar.h

#ifndef MY_CHAR_H
#define MY_CHAR_H
 
#include <asm/ioctl.h>
 
#define MY_CHAR_MAGIC 'k'
 
#define MYCHAR_IOCTL_GET_MAXLEN _IOR(MY_CHAR_MAGIC,1,int*)
#define MYCHAR_IOCTL_GET_CURLEN _IOR(MY_CHAR_MAGIC,2,int*)
 
 
#endif

mychar_poll.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/poll.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
 
#include "mychar.h"
 
#define BUF_LEN 100
 
int major = 11;
int minor = 0;
int mychar_num  = 1;
 
struct mychar_dev
{
    struct cdev mydev;
 
    char mydev_buf[BUF_LEN];
    int curlen;
    struct mutex lock;
 
    wait_queue_head_t rq;
    wait_queue_head_t wq;
 
    struct fasync_struct *pasync_obj;
};
 
struct mychar_dev *pgmydev = NULL;
 
int mychar_open(struct inode *pnode,struct file *pfile)
{
    pfile->private_data =(void *) (container_of(pnode->i_cdev,struct mychar_dev,mydev));
    return 0;
}
 
int mychar_close(struct inode *pnode,struct file *pfile)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    if(pmydev->pasync_obj != NULL)
        fasync_helper(-1,pfile,0,&pmydev->pasync_obj);
    return 0;
}
 
ssize_t mychar_read(struct file *pfile,char __user *puser,size_t count,loff_t *p_pos)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
    int size = 0;
    int ret = 0;
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen <= 0)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {//非阻塞
            mutex_unlock(&pmydev->lock);
            printk("O_NONBLOCK No Data Read\n");
            return -1;
        }
        else
        {//阻塞
            mutex_unlock(&pmydev->lock);
            ret = wait_event_interruptible(pmydev->rq,pmydev->curlen > 0);
            if(ret)
            {
                printk("Wake up by signal\n");
                return -ERESTARTSYS;
            }
            mutex_lock(&pmydev->lock);
        }
    }
 
    if(count > pmydev->curlen)
    {
        size = pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_to_user(puser,pmydev->mydev_buf,size);
    if(ret)
    {
        mutex_unlock(&pmydev->lock);
        printk("copy_to_user failed\n");
        return -1;
    }
 
    memcpy(pmydev->mydev_buf,pmydev->mydev_buf + size,pmydev->curlen - size);
 
    pmydev->curlen -= size;
 
    mutex_unlock(&pmydev->lock);
 
    wake_up_interruptible(&pmydev->wq);
    return size;
}
 
ssize_t mychar_write(struct file *pfile,const char __user *puser,size_t count,loff_t *p_pos)
{
    int size = 0;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen >= BUF_LEN)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {
            mutex_unlock(&pmydev->lock);
            printk("O_NONBLOCK Can not write data\n");
            return -1;
        }
        else
        {
            mutex_unlock(&pmydev->lock);
            ret = wait_event_interruptible(pmydev->wq,pmydev->curlen < BUF_LEN);
            if(ret)
            {
                printk("wake up by signal\n");
                return -ERESTARTSYS;
            }
            mutex_lock(&pmydev->lock);
        }
    }
 
    if(count > BUF_LEN-pmydev->curlen)
    {
        size = BUF_LEN - pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_from_user(pmydev->mydev_buf + pmydev->curlen,puser,size);
    if(ret)
    {
        mutex_unlock(&pmydev->lock);
        printk("copy_from_user failed\n");
        return -1;
    }
    pmydev->curlen  +=  size;
 
    mutex_unlock(&pmydev->lock);
 
    wake_up_interruptible(&pmydev->rq);
 
    if(pmydev->pasync_obj != NULL)
    {
        kill_fasync(&pmydev->pasync_obj,SIGIO,POLL_IN);
    }
 
    return size;
}
 
long mychar_ioctl(struct file *pfile,unsigned int cmd,unsigned long arg)
{
    int __user *pret = (int *)arg;
    int maxlen = BUF_LEN;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    switch(cmd)
    {
        case MYCHAR_IOCTL_GET_MAXLEN:
            ret = copy_to_user(pret,&maxlen,sizeof(int));
            if(ret)
            {
                printk("copy_to_user MAXLEN failed\n");
                return -1;
            }
            break;
        case MYCHAR_IOCTL_GET_CURLEN:
            mutex_lock(&pmydev->lock);
            ret = copy_to_user(pret,&pmydev->curlen,sizeof(int));
            mutex_unlock(&pmydev->lock);
            if(ret)
            {
                printk("copy_to_user CURLEN failed\n");
                return -1;
            }
            break;
        default:
            printk("The cmd is unknow\n");
            return -1;
 
    }
 
    return 0;
}
 
unsigned int mychar_poll(struct file *pfile,poll_table *ptb)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
    unsigned int mask = 0;
 
    poll_wait(pfile,&pmydev->rq,ptb);
    poll_wait(pfile,&pmydev->wq,ptb);
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen > 0)
    {
        mask |= POLLIN | POLLRDNORM;
    }
    if(pmydev->curlen < BUF_LEN)
    {
        mask |= POLLOUT | POLLWRNORM;
    }
    mutex_unlock(&pmydev->lock);
 
    return mask;
}
 
struct file_operations myops = {
    .owner = THIS_MODULE,
    .open = mychar_open,
    .release = mychar_close,
    .read = mychar_read,
    .write = mychar_write,
    .unlocked_ioctl = mychar_ioctl,
    .poll = mychar_poll,
};
 
int __init mychar_init(void)
{
    int ret = 0;
    dev_t devno = MKDEV(major,minor);
 
    /*申请设备号*/
    ret = register_chrdev_region(devno,mychar_num,"mychar");
    if(ret)
    {
        ret = alloc_chrdev_region(&devno,minor,mychar_num,"mychar");
        if(ret)
        {
            printk("get devno failed\n");
            return -1;
        }
        major = MAJOR(devno);//容易遗漏,注意
    }
 
    pgmydev = (struct mychar_dev *)kmalloc(sizeof(struct mychar_dev),GFP_KERNEL);
    if(NULL == pgmydev)
    {
        unregister_chrdev_region(devno,mychar_num);
        printk("kmallc for struct mychar_dev failed\n");
        return -1;
    }
 
    /*给struct cdev对象指定操作函数集*/  
    cdev_init(&pgmydev->mydev,&myops);
 
    /*将struct cdev对象添加到内核对应的数据结构里*/
    pgmydev->mydev.owner = THIS_MODULE;
    cdev_add(&pgmydev->mydev,devno,mychar_num);
 
 
    init_waitqueue_head(&pgmydev->rq);
    init_waitqueue_head(&pgmydev->wq);
 
    mutex_init(&pgmydev->lock);
    return 0;
}
 
void __exit mychar_exit(void)
{
    dev_t devno = MKDEV(major,minor);
 
    cdev_del(&pgmydev->mydev);
 
    unregister_chrdev_region(devno,mychar_num);
 
    kfree(pgmydev);
    pgmydev = NULL;
}
 
 
MODULE_LICENSE("GPL");
 
module_init(mychar_init);
module_exit(mychar_exit);

mychar_test_app.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
 
 
#include <stdio.h>
 
#include "mychar.h"
int main(int argc,char *argv[])
{
    int fd = -1;
    char buf[8] = "";
    int ret = 0;
    fd_set rfds;
 
    if(argc < 2)
    {
        printf("The argument is too few\n");
        return 1;
    }
 
    fd = open(argv[1],O_RDWR);
    if(fd < 0)
    {
        printf("open %s failed\n",argv[1]);
        return 2;
    }
 
    while(1)
    {
        FD_ZERO(&rfds);
        FD_SET(fd,&rfds);
        ret = select(fd + 1,&rfds,NULL,NULL,NULL);
        if(ret < 0)
        {
            if(errno == EINTR)
            {
                continue;
            }
            else
            {
                printf("select error\n");
                break;
            }
        }
        if(FD_ISSET(fd,&rfds))
        {
            read(fd,buf,8);
            printf("buf=%s\n",buf);
        }
    }
 
 
 
    close(fd);
    fd = -1;
    return 0;
}

四、信号驱动

4.1 应用层:信号注册+fcntl

signal(SIGIO, input_handler); //注册信号处理函数

fcntl(fd, F_SETOWN, getpid());//将描述符设置给对应进程,好由描述符获知PID

oflags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, oflags | FASYNC);//将该设备的IO模式设置成信号驱动模式

void input_handler(int signum)//应用自己实现的信号处理函数,在此函数中完成读写
{
    //读数据
}

//应用模板
int main()
{
	int fd = open("/dev/xxxx",O_RDONLY);

	fcntl(fd, F_SETOWN, getpid());

	oflags = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, oflags | FASYNC);

	signal(SIGIO,xxxx_handler);

	//......
}
    
void xxxx_handle(int signo)
{//读写数据
    
}


4.2 驱动层:实现fasync函数

/*设备结构中添加如下成员*/
struct fasync_struct *pasync_obj;

/*应用调用fcntl设置FASYNC时调用该函数产生异步通知结构对象,并将其地址设置到设备结构成员中*/
static int hello_fasync(int fd, struct file *filp, int mode) //函数名初始化给struct file_operations的成员.fasync
{
	struct hello_device *dev = filp->private_data; 
	return fasync_helper(fd, filp, mode, &dev->pasync_obj);
}

/*写函数中有数据可读时向应用层发信号*/
if (dev->pasync_obj)
       kill_fasync(&dev->pasync_obj, SIGIO, POLL_IN);
       
/*release函数中释放异步通知结构对象*/
if (dev->pasync_obj) 
	fasync_helper(-1, filp, 0, &dev->pasync_obj);

int fasync_helper(int fd, struct file *filp, int mode, struct fasync_struct **pp);
/*
	功能:产生或释放异步通知结构对象
	参数:
	返回值:成功为>=0,失败负数
*/

void kill_fasync(struct fasync_struct **, int, int);
/*	
	功能:发信号
	参数:
		struct fasync_struct ** 指向保存异步通知结构地址的指针
		int 	信号 SIGIO/SIGKILL/SIGCHLD/SIGCONT/SIGSTOP
		int 	读写信息POLLIN、POLLOUT
*/

4.3代码示例

mychar_signal.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/poll.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
 
#include "mychar.h"
 
#define BUF_LEN 100
 
int major = 11;
int minor = 0;
int mychar_num  = 1;
 
struct mychar_dev
{
    struct cdev mydev;
 
    char mydev_buf[BUF_LEN];
    int curlen;
    struct mutex lock;
 
    wait_queue_head_t rq;
    wait_queue_head_t wq;
 
    struct fasync_struct *pasync_obj;
};
 
struct mychar_dev *pgmydev = NULL;
 
int mychar_open(struct inode *pnode,struct file *pfile)
{
    pfile->private_data =(void *) (container_of(pnode->i_cdev,struct mychar_dev,mydev));
    return 0;
}
 
int mychar_close(struct inode *pnode,struct file *pfile)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    if(pmydev->pasync_obj != NULL)
        fasync_helper(-1,pfile,0,&pmydev->pasync_obj);
    return 0;
}
 
ssize_t mychar_read(struct file *pfile,char __user *puser,size_t count,loff_t *p_pos)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
    int size = 0;
    int ret = 0;
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen <= 0)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {//非阻塞
            mutex_unlock(&pmydev->lock);
            printk("O_NONBLOCK No Data Read\n");
            return -1;
        }
        else
        {//阻塞
            mutex_unlock(&pmydev->lock);
            ret = wait_event_interruptible(pmydev->rq,pmydev->curlen > 0);
            if(ret)
            {
                printk("Wake up by signal\n");
                return -ERESTARTSYS;
            }
            mutex_lock(&pmydev->lock);
        }
    }
 
    if(count > pmydev->curlen)
    {
        size = pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_to_user(puser,pmydev->mydev_buf,size);
    if(ret)
    {
        mutex_unlock(&pmydev->lock);
        printk("copy_to_user failed\n");
        return -1;
    }
 
    memcpy(pmydev->mydev_buf,pmydev->mydev_buf + size,pmydev->curlen - size);
 
    pmydev->curlen -= size;
 
    mutex_unlock(&pmydev->lock);
 
    wake_up_interruptible(&pmydev->wq);
    return size;
}
 
ssize_t mychar_write(struct file *pfile,const char __user *puser,size_t count,loff_t *p_pos)
{
    int size = 0;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen >= BUF_LEN)
    {
        if(pfile->f_flags & O_NONBLOCK)
        {
            mutex_unlock(&pmydev->lock);
            printk("O_NONBLOCK Can not write data\n");
            return -1;
        }
        else
        {
            mutex_unlock(&pmydev->lock);
            ret = wait_event_interruptible(pmydev->wq,pmydev->curlen < BUF_LEN);
            if(ret)
            {
                printk("wake up by signal\n");
                return -ERESTARTSYS;
            }
            mutex_lock(&pmydev->lock);
        }
    }
 
    if(count > BUF_LEN-pmydev->curlen)
    {
        size = BUF_LEN - pmydev->curlen;
    }
    else
    {
        size = count;
    }
 
    ret = copy_from_user(pmydev->mydev_buf + pmydev->curlen,puser,size);
    if(ret)
    {
        mutex_unlock(&pmydev->lock);
        printk("copy_from_user failed\n");
        return -1;
    }
    pmydev->curlen  +=  size;
 
    mutex_unlock(&pmydev->lock);
 
    wake_up_interruptible(&pmydev->rq);
 
    if(pmydev->pasync_obj != NULL)
    {
        kill_fasync(&pmydev->pasync_obj,SIGIO,POLL_IN);
    }
 
    return size;
}
 
long mychar_ioctl(struct file *pfile,unsigned int cmd,unsigned long arg)
{
    int __user *pret = (int *)arg;
    int maxlen = BUF_LEN;
    int ret = 0;
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    switch(cmd)
    {
        case MYCHAR_IOCTL_GET_MAXLEN:
            ret = copy_to_user(pret,&maxlen,sizeof(int));
            if(ret)
            {
                printk("copy_to_user MAXLEN failed\n");
                return -1;
            }
            break;
        case MYCHAR_IOCTL_GET_CURLEN:
            mutex_lock(&pmydev->lock);
            ret = copy_to_user(pret,&pmydev->curlen,sizeof(int));
            mutex_unlock(&pmydev->lock);
            if(ret)
            {
                printk("copy_to_user CURLEN failed\n");
                return -1;
            }
            break;
        default:
            printk("The cmd is unknow\n");
            return -1;
 
    }
 
    return 0;
}
 
unsigned int mychar_poll(struct file *pfile,poll_table *ptb)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
    unsigned int mask = 0;
 
    poll_wait(pfile,&pmydev->rq,ptb);
    poll_wait(pfile,&pmydev->wq,ptb);
 
    mutex_lock(&pmydev->lock);
    if(pmydev->curlen > 0)
    {
        mask |= POLLIN | POLLRDNORM;
    }
    if(pmydev->curlen < BUF_LEN)
    {
        mask |= POLLOUT | POLLWRNORM;
    }
    mutex_unlock(&pmydev->lock);
 
    return mask;
}
 
int mychar_fasync(int fd,struct file *pfile,int mode)
{
    struct mychar_dev *pmydev = (struct mychar_dev *)pfile->private_data;
 
    return fasync_helper(fd,pfile,mode,&pmydev->pasync_obj);
}
 
struct file_operations myops = {
    .owner = THIS_MODULE,
    .open = mychar_open,
    .release = mychar_close,
    .read = mychar_read,
    .write = mychar_write,
    .unlocked_ioctl = mychar_ioctl,
    .poll = mychar_poll,
    .fasync = mychar_fasync,
};
 
int __init mychar_init(void)
{
    int ret = 0;
    dev_t devno = MKDEV(major,minor);
 
    /*申请设备号*/
    ret = register_chrdev_region(devno,mychar_num,"mychar");
    if(ret)
    {
        ret = alloc_chrdev_region(&devno,minor,mychar_num,"mychar");
        if(ret)
        {
            printk("get devno failed\n");
            return -1;
        }
        major = MAJOR(devno);//容易遗漏,注意
    }
 
    pgmydev = (struct mychar_dev *)kmalloc(sizeof(struct mychar_dev),GFP_KERNEL);
    if(NULL == pgmydev)
    {
        unregister_chrdev_region(devno,mychar_num);
        printk("kmallc for struct mychar_dev failed\n");
        return -1;
    }
 
    /*给struct cdev对象指定操作函数集*/  
    cdev_init(&pgmydev->mydev,&myops);
 
    /*将struct cdev对象添加到内核对应的数据结构里*/
    pgmydev->mydev.owner = THIS_MODULE;
    cdev_add(&pgmydev->mydev,devno,mychar_num);
 
 
    init_waitqueue_head(&pgmydev->rq);
    init_waitqueue_head(&pgmydev->wq);
 
    mutex_init(&pgmydev->lock);
    return 0;
}
 
void __exit mychar_exit(void)
{
    dev_t devno = MKDEV(major,minor);
 
    cdev_del(&pgmydev->mydev);
 
    unregister_chrdev_region(devno,mychar_num);
 
    kfree(pgmydev);
    pgmydev = NULL;
}
 
 
MODULE_LICENSE("GPL");
 
module_init(mychar_init);
module_exit(mychar_exit);

mychar_test_app.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <signal.h>
 
#include <stdio.h>
 
#include "mychar.h"
int fd = -1;
 
void sigio_handler(int signo);
int main(int argc,char *argv[])
{
    int flg = 0;
 
    if(argc < 2)
    {
        printf("The argument is too few\n");
        return 1;
    }
 
    signal(SIGIO,sigio_handler);
 
    fd = open(argv[1],O_RDWR);
    if(fd < 0)
    {
        printf("open %s failed\n",argv[1]);
        return 2;
    }
 
    fcntl(fd,F_SETOWN,getpid());
 
    flg = fcntl(fd,F_GETFL);
    flg |= FASYNC;
    fcntl(fd,F_SETFL,flg);
 
    while(1)
    {
    }
 
    close(fd);
    fd = -1;
    return 0;
}
 
void sigio_handler(int signo)
{
    char buf[8] = "";
    read(fd,buf,8);
    printf("buf=%s\n",buf);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值