Linux驱动中completion接口浅析(wait_for_complete例子,很好)【转】

简介: 转自:http://blog.csdn.net/batoom/article/details/6298267  completion是一种轻量级的机制,它允许一个线程告诉另一个线程工作已经完成。可以利用下面的宏静态创建completion:                         DECL...

转自:http://blog.csdn.net/batoom/article/details/6298267

 completion是一种轻量级的机制,它允许一个线程告诉另一个线程工作已经完成。可以利用下面的宏静态创建completion:
                         DECLARE_COMPLETION(my_completion); 
       

        如果运行时创建completion,则必须采用以下方法动态创建和初始化:
                         struct compltion my_completion;
                          init_completion(&my_completion);

        completion的相关定义包含在kernel/include/linux/completion.h中:

                        struct completion {
                                     unsigned int done;
                                     wait_queue_head_t wait;
                         };


#define COMPLETION_INITIALIZER(work) /
                                                           { 0, __WAIT_QUEUE_HEAD_INITIALIZER((work).wait) }

#define DECLARE_COMPLETION(work) /
                                                      struct completion work = COMPLETION_INITIALIZER(work)

static inline void init_completion(struct completion *x)
{
          x->done = 0;
          init_waitqueue_head(&x->wait);
}

       要等待completion,可进行如下调用:
                    void wait_for_completion(struct completion *c);

       触发completion事件,调用:
                   void complete(struct completion *c);    //唤醒一个等待线程
                   void complete_all(struct completion *c);//唤醒所有的等待线程

        为说明completion的使用方法,将《Linux设备驱动程序》一书中的complete模块的代码摘抄如下:
/*
* complete.c -- the writers awake the readers
*
* Copyright (C) 2003 Alessandro Rubini and Jonathan Corbet
* Copyright (C) 2003 O'Reilly & Associates
*
* The source code in this file can be freely used, adapted,
* and redistributed in source or binary form, so long as an
* acknowledgment appears in derived source files.    The citation
* should list that the code comes from the book "Linux Device
* Drivers" by Alessandro Rubini and Jonathan Corbet, published
* by O'Reilly & Associates.     No warranty is attached;
* we cannot take responsibility for errors or fitness for use.
*
* $Id: complete.c,v 1.2 2004/09/26 07:02:43 gregkh Exp $
*/

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

#include <linux/sched.h>   /* current and everything */
#include <linux/kernel.h> /* printk() */
#include <linux/fs.h>      /* everything... */
#include <linux/types.h>   /* size_t */
#include <linux/completion.h>

MODULE_LICENSE("Dual BSD/GPL");

static int complete_major = 253;//指定主设备号

DECLARE_COMPLETION(comp);

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

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


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


int complete_init(void)
{
         int result;

/*
    * Register your major, and accept a dynamic number
    */
        result = register_chrdev(complete_major, "complete", &complete_fops);
        if (result < 0)
                return result;
        if (complete_major == 0)
                complete_major = result; /* dynamic */
        return 0;
}

void complete_cleanup(void)
{
         unregister_chrdev(complete_major, "complete");
}

module_init(complete_init);
module_exit(complete_cleanup);


        该模块定义了一个简单的completion设备:任何试图从该设备中读取的进程都将等待,直到其他设备写入该设备为止。编译此模块的Makefile如下:
obj-m := complete.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod.c

在linux终端中执行以下命令,编译生成模块,并进行动态加载。
#make
#mknod completion c 253 0
#insmod complete.ko
再打开三个终端,一个用于读进程:
#cat completion
一个用于写进程:
#echo >completion
另一个查看系统日志:
#tail -f /var/log/messages

         值得注意的是,当我们使用的complete_all接口时,如果要重复使用一个completion结构,则必须执行 INIT_COMPLETION(struct completion c)来重新初始化它。可以在kernel/include/linux/completion.h中找到这个宏的定义:
          #define INIT_COMPLETION(x) ((x).done = 0)

        以下代码对书中原有的代码进行了一番变动,将唤醒接口由原来的complete换成了complete_all,并且为了重复利用completion结构,所有读进程都结束后就重新初始化completion结构,具体代码如下:
#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("Dual BSD/GPL");

#undef KERN_DEBUG
#define KERN_DEBUG "<1>"

static int complete_major=253;
static int reader_count = 0;

DECLARE_COMPLETION(comp);

ssize_t complete_read (struct file *filp,char __user *buf,size_t count,loff_t *pos)
{
           printk(KERN_DEBUG "process %i (%s) going to sleep,waiting for writer/n",current->pid,current->comm);
           reader_count++;
           printk(KERN_DEBUG "In read ,before comletion: reader count = %d /n",reader_count);
           wait_for_completion(&comp);
           reader_count--;
           printk(KERN_DEBUG "awoken %s (%i) /n",current->comm,current->pid);
           printk(KERN_DEBUG "In read,after completion : reader count = %d /n",reader_count);

/*如果使用complete_all,则completion结构只能用一次,再次使用它时必须调用此宏进行重新初始化*/
           if(reader_count == 0)
                       INIT_COMPLETION(comp);

           return 0;
}

ssize_t complete_write(struct file *filp,const char __user *buf,size_t count,loff_t *pos)
{
           printk(KERN_DEBUG "process %i (%s) awoking the readers.../n",current->pid,current->comm);
           printk(KERN_DEBUG "In write ,before do complete_all : reader count = %d /n",reader_count);

           if(reader_count != 0)  
                   complete_all(&comp);

           printk(KERN_DEBUG "In write ,after do complete_all : reader count = %d /n",reader_count);

           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;

           printk(KERN_DEBUG    "complete driver test init! complete_major=%d/n",complete_major);
           printk(KERN_DEBUG "静态初始化completion/n");

           return 0;
}

void complete_exit(void)
{
           unregister_chrdev(complete_major,"complete");
           printk(KERN_DEBUG    "complete driver    is removed/n");
}

module_init(complete_init);
module_exit(complete_exit);

这里测试步骤和上述一样,只不过需要多打开几个终端来执行多个进程同时读操作。

____________

参考资料:
1.Jonathan Corbet等著,魏永明等译.linux设备驱动程序(第三版)
2.Linux Kernel

【作者】 张昺华
【新浪微博】 张昺华--sky
【twitter】 @sky2030_
【facebook】 张昺华 zhangbinghua
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
目录
相关文章
|
2月前
|
Linux 应用服务中间件 Shell
二、Linux文本处理与文件操作核心命令
熟悉了Linux的基本“行走”后,就该拿起真正的“工具”干活了。用grep这个“放大镜”在文件里搜索内容,用find这个“探测器”在系统中寻找文件,再用tar把东西打包带走。最关键的是要学会使用管道符|,它像一条流水线,能把这些命令串联起来,让简单工具组合出强大的功能,比如 ps -ef | grep 'nginx' 就能快速找出nginx进程。
409 1
二、Linux文本处理与文件操作核心命令
|
2月前
|
Linux
linux命令—stat
`stat` 是 Linux 系统中用于查看文件或文件系统详细状态信息的命令。相比 `ls -l`,它提供更全面的信息,包括文件大小、权限、所有者、时间戳(最后访问、修改、状态变更时间)、inode 号、设备信息等。其常用选项包括 `-f` 查看文件系统状态、`-t` 以简洁格式输出、`-L` 跟踪符号链接,以及 `-c` 或 `--format` 自定义输出格式。通过这些选项,用户可以灵活获取所需信息,适用于系统调试、权限检查、磁盘管理等场景。
288 137
|
2月前
|
安全 Ubuntu Unix
一、初识 Linux 与基本命令
玩转Linux命令行,就像探索一座新城市。首先要熟悉它的“地图”,也就是/根目录下/etc(放配置)、/home(住家)这些核心区域。然后掌握几个“生存口令”:用ls看周围,cd去别处,mkdir建新房,cp/mv搬东西,再用cat或tail看文件内容。最后,别忘了随时按Tab键,它能帮你自动补全命令和路径,是提高效率的第一神器。
659 57
|
5月前
|
JSON 自然语言处理 Linux
linux命令—tree
tree是一款强大的Linux命令行工具,用于以树状结构递归展示目录和文件,直观呈现层级关系。支持多种功能,如过滤、排序、权限显示及格式化输出等。安装方法因系统而异常用场景包括:基础用法(显示当前或指定目录结构)、核心参数应用(如层级控制-L、隐藏文件显示-a、完整路径输出-f)以及进阶操作(如磁盘空间分析--du、结合grep过滤内容、生成JSON格式列表-J等)。此外,还可生成网站目录结构图并导出为HTML文件。注意事项:使用Tab键补全路径避免错误;超大目录建议限制遍历层数;脚本中推荐禁用统计信息以优化性能。更多详情可查阅手册mantree。
491 143
linux命令—tree
|
1月前
|
存储 安全 Linux
Linux卡在emergency mode怎么办?xfs_repair 命令轻松解决
Linux虚拟机遇紧急模式?别慌!多因磁盘挂载失败。本文教你通过日志定位问题,用`xfs_repair`等工具修复文件系统,三步快速恢复。掌握查日志、修磁盘、验重启,轻松应对紧急模式,保障系统稳定运行。
369 2
|
2月前
|
缓存 监控 Linux
Linux内存问题排查命令详解
Linux服务器卡顿?可能是内存问题。掌握free、vmstat、sar三大命令,快速排查内存使用情况。free查看实时内存,vmstat诊断系统整体性能瓶颈,sar实现长期监控,三者结合,高效定位并解决内存问题。
250 0
Linux内存问题排查命令详解
|
2月前
|
Unix Linux 程序员
Linux文本搜索工具grep命令使用指南
以上就是对Linux环境下强大工具 `grep` 的基础到进阶功能介绍。它不仅能够执行简单文字查询任务还能够处理复杂文字处理任务,并且支持强大而灵活地正则表达规范来增加查询精度与效率。无论您是程序员、数据分析师还是系统管理员,在日常工作中熟练运用该命令都将极大提升您处理和分析数据效率。
258 16
|
4月前
|
监控 Linux 网络安全
Linux命令大全:从入门到精通
日常使用的linux命令整理
803 13
|
5月前
|
Linux 网络安全 数据安全/隐私保护
使用Linux系统的mount命令挂载远程服务器的文件夹。
如此一来,你就完成了一次从你的Linux发车站到远程服务器文件夹的有趣旅行。在这个技术之旅中,你既探索了新地方,也学到了如何桥接不同系统之间的距离。
914 21
|
5月前
|
监控 Linux
Linux系统中使用df命令详解磁盘使用情况。
`df`命令是Linux系统管理员和用户监控和管理磁盘空间使用的重要工具。掌握它的基本使用方法和选项可以帮助在必要时分析和解决空间相关问题。简洁但功能丰富,`df`命令确保了用户可以快速有效地识别和管理文件系统的空间使用情况。
414 13