嵌入式linux:阻塞与非阻塞驱动

本文介绍了如何在嵌入式Linux系统中编写一个虚拟驱动,该驱动在读取操作时会阻塞,直到接收到数据后再进行读取。通过信号量和IO操作的运用,实现了阻塞与非阻塞模式的切换。同时,作者还编写了应用程序来验证驱动的正确性。
摘要由CSDN通过智能技术生成

编写了一个虚拟的驱动,实现的功能是在读设备时阻塞,直到有数据写入设备,然后才能读出写入的数据。

其中有信号量的操作与阻塞非阻塞IO的操作,

最后写了一个应用程序进行验证

驱动如下:

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/cdev.h>
#include <linux/device.h>

/*for spinlock and semaphore*/
#include <asm/spinlock.h>
#include <linux/spinlock.h>
#include <linux/semaphore.h>
 
/*for task management*/
#include <linux/wait.h>
#include <linux/types.h>
#include <linux/sched.h>

#define DEVICE_NAME "pcio"
#define DRIVER_NAME "mypcio"//加载驱动之后会在/dev/目录下发现mypcio,应用程序可以使用

#define PCIO_MAJOR 0 //预设的pcio的主设备号


static int pcio_major = PCIO_MAJOR;
static int pcioOpenCount=0;
static int flag=0;
static int global_var = 0;

struct class *pcio_class;
static struct device *pcioDevice=NULL;

static wait_queue_head_t wqueue;


struct pcio_dev
{
   struct cdev cdev;//cdev结构体
   //信号量
   struct semaphore sem;
   //等待队列头
   //struct wait_queue_head_t* wqueue;
   //unsigned char mem[MYKEY_SIZE];//全局内存
};
struct pcio_dev *pcio_devp;//设备结构体指针

//打开函数
static int pcio_open(struct inode *inode, struct file *file)
{
   pcioOpenCount++;
   return 0;
}
//关闭函数
static int pcio_close(struct inode *inode, struct file *file)
{
   pcioOpenCount--;
   return 0;
}
//读函数
static ssize_t pcio_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
   //等待事件
   if(wait_event_interruptible(wqueue,flag!=0))
   {
      return -ERESTARTSYS;
   }
   //获取信号量
   if(down_interruptible(&pcio_devp->sem))
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值