内核阻塞式IO

static ssize_t fifo_read (struct file *f, char __user *p, size_t n, loff_t *off)
{
	int size;
	if(FIFO.cursize == 0)
		//let this procss go to sleep
		wait_event_interruptible(FIFO.readqueue, FIFO.cursize != 0);

	size = n>FIFO.cursize?FIFO.cursize:n;
//		return 0;
	int len1, len2;
	if(FIFO.start <= FIFO.end)// copy once
	{
		if(copy_to_user(p, FIFO.qbuf, size))
		{
			printk("copy to user fail1\n");
			return -EINVAL;
		}
	}
	else
	{
		len1 = FIFO.maxsize-FIFO.start;
		if(copy_to_user(p, &FIFO.qbuf[FIFO.start], len1))
		{
			printk("copy to user fail2\n");
			return -EINVAL;
		}
		len2 = size-len1;
		if(copy_to_user(p+len1, FIFO.qbuf, len2))
		{
			printk("copy to user fail3\n");
			return -EINVAL;
		}
	}

	FIFO.start = (FIFO.start+size)%FIFO.maxsize;
	FIFO.cursize -= size;
	
	
	return size;
}

static ssize_t fifo_write (struct file *f, const char __user *p, size_t n, loff_t *off)
{
	int space = FIFO.maxsize - FIFO.cursize;
	int size = n>space?space:n;
	int len1 = (FIFO.maxsize-1 - FIFO.end);
	int len2;
	if(!space)
		return 0;
	
//	copy_from_user(&FIFO.qbuf[end+1], p, size);
	if(len1 >= size)//copy once
	{
		if(copy_from_user(&FIFO.qbuf[FIFO.end+1], p, size))
		{
			printk("copy from user fail1\n");
			return -EINVAL;
		}
	}
	else
	{
		if(copy_from_user(&FIFO.qbuf[FIFO.end+1], p, len1))
		{
			printk("copy from user fail2\n");
			return -EINVAL;
		}
		len2 = size-len1;
		if(copy_from_user(FIFO.qbuf, p+len1,  len2))
		{
			printk("copy from user fail3\n");
			return -EINVAL;
		}
	}
	FIFO.end = (FIFO.end+size)%FIFO.maxsize;
	FIFO.cursize += size;
	
	//woke up processes
	wake_up_interruptible(&FIFO.readqueue);
//	wake_up(&FIFO.readqueue);

	return size;
}
总结:利用等待队列机制构建内核阻塞IO模型
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值