Linux内核同步机制之completion

发表于:2012-3-29 09:57

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:bullbat的专栏

  而complete实现如下:

void complete(struct completion *x)
{
 unsigned long flags;

 spin_lock_irqsave(&x->wait.lock, flags);
 x->done++;
 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
 spin_unlock_irqrestore(&x->wait.lock, flags);
}

  不看内核实现的源代码我们也能想到他的实现,不外乎在wait函数中循环等待done变为可用(正),而另一边的complete函数为唤醒函数,当然是将done加一,唤醒待处理的函数。是的,从上面的代码看到,和我们想的一样。内核也是这样做的。

  运用

  运用LDD3中的例子:

#include <linux/module.h>
#include <linux/init.h>

#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/completion.h>

MODULE_LICENSE("GPL");

static int complete_major=250;
DECLARE_COMPLETION(comp);

ssize_t complete_read(struct file *filp,char __user *buf,size_t count,loff_t *pos)
{
 printk(KERN_ERR "process %i (%s) going to sleep\n",current->pid,current->comm);
 wait_for_completion(&comp);
 printk(KERN_ERR "awoken %i (%s)\n",current->pid,current->comm);
 return 0;
}

ssize_t complete_write(struct file *filp,const char __user *buf,size_t count,loff_t *pos)
{
 printk(KERN_ERR "process %i (%s) awakening the readers...\n",current->pid,current->comm);
 complete(&comp);
 return count;
}

struct file_operations complete_fops={
 .owner=THIS_MODULE,
 .read=complete_read,
 .write=complete_write,
};

int complete_init(void)
{
 int result;
 result=register_chrdev(complete_major,"complete",&complete_fops);
 if(result<0)
  return result;
 if(complete_major==0)
  complete_major=result;
 return 0;
}
void complete_cleanup(void)
{
 unregister_chrdev(complete_major,"complete");
}
module_init(complete_init);
module_exit(complete_cleanup);

  测试步骤:

  1、mknod /dev/complete创建complete节点,在linux上驱动程序需要手动创建文件节点。

  2、insmod complete.ko 插入驱动模块,这里要注意的是,因为我们的代码中是手动分配的设备号,很可能被系统已经使用了,所以如果出现这种情况,查看/proc/devices文件。找一个没有被使用的设备号。

  3、cat /dev/complete 用于读该设备,调用设备的读函数

  4、打开另一个终端输入 echo “hello” > /dev/complete 该命令用于写入该设备。

22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号