zoukankan      html  css  js  c++  java
  • 实验

    驱动文件hello.c

    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/fs.h>
    #include <linux/init.h>
    #include <linux/delay.h>
    
    #define    HELLO_MAJOR     231
    #define    DEVICE_NAME     "HelloModule"
    
    static int hello_open(struct inode *inode, struct file *file){
        printk(KERN_EMERG "hello open.
    ");
        return 0;
    }
    
    static int hello_write(struct file *file, const char __user * buf, size_t count, loff_t *ppos){
        printk(KERN_EMERG "hello write.
    ");
        return 0;
    }
    
    static struct file_operations hello_flops = {
        .owner  =   THIS_MODULE,
        .open   =   hello_open,     
        .write  =   hello_write,
    };
    
    static int __init hello_init(void){
        int ret;
        
        ret = register_chrdev(HELLO_MAJOR,DEVICE_NAME, &hello_flops);
        if (ret < 0) {
          printk(KERN_EMERG DEVICE_NAME " can't register major number.
    ");
          return ret;
        }
        printk(KERN_EMERG DEVICE_NAME " initialized.
    ");
        return 0;
    }
    
    static void __exit hello_exit(void){
        unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
        printk(KERN_EMERG DEVICE_NAME " removed.
    ");
    }
    
    module_init(hello_init);
    module_exit(hello_exit);
    MODULE_LICENSE("GPL");
    

    编译驱动所需的Makefile

    ifneq ($(KERNELRELEASE),)
    MODULE_NAME = hellomodule
    $(MODULE_NAME)-objs := hello.o
    obj-m := $(MODULE_NAME).o
    else
    KERNEL_DIR = /lib/modules/`uname -r`/build
    MODULEDIR := $(shell pwd)
    
    .PHONY: modules
    default: modules
    
    modules:
        make -C $(KERNEL_DIR) M=$(MODULEDIR) modules
    
    clean distclean:
        rm -f *.o *.mod.c .*.*.cmd *.ko
        rm -rf .tmp_versions
    endif
    

    1、编译驱动

    #make
    

    2、编译上层应用

    #gcc hellotest.c -o hellotest
    

    3、加载驱动

    #insmod hellomodule.ko
    

    insmod加载驱动的时候,会调用函数hello_init(),打印的调试信息如下。

    但是在"/proc/devices"中看不到已经加载的模块。

  • 相关阅读:
    P2207 Photo
    P1022 计算器的改良
    P1003 铺地毯
    P3014 [USACO11FEB]牛线Cow Line && 康托展开
    P4180 【模板】严格次小生成树[BJWC2010]
    P2776 [SDOI2007]小组队列
    P2426 删数
    P1948 [USACO08JAN]电话线Telephone Lines
    P1978 集合
    P1564 膜拜
  • 原文地址:https://www.cnblogs.com/lsqz/p/12080574.html
Copyright © 2011-2022 走看看