您的位置:首页 > 运维架构 > Linux

Linux Driver 入门-1

2013-10-25 15:07 447 查看
first_cdev_module.c :

#include <linux/init.h>

#include <linux/module.h>

#include <linux/kernel.h>

#include <linux/cdev.h>

#include <linux/slab.h>

#include <linux/fs.h>

#include <linux/device.h>

MODULE_LICENSE("GPL");

static dev_t dev_id;

static struct cdev *my_cdev;

static struct class *first_drv_class;

static struct device *first_drv_class_device;

static ssize_t first_cdrv_read (struct file * file, char __user * buf, size_t count, loff_t *offset)

{

    printk(KERN_ALERT"first_cdrv_read start.\n");

    return 0;  

}

static ssize_t first_cdrv_write (struct file * file, const char __user * buf, size_t count, loff_t *offset)

{

    printk(KERN_ALERT"first_cdrv_write start.\n");

    return 0;  

}

static int first_cdrv_release (struct inode * inode, struct file * file)

{

    printk(KERN_ALERT"first_cdrv_release releasing.\n");

    return 0;

}

static int first_cdrv_open (struct inode * inode, struct file * file)

{

    printk(KERN_ALERT"first_cdrv_open start.\n");

    return 0;  

}

struct file_operations fops ={

    .owner = THIS_MODULE,

    .open = first_cdrv_open,

    .read = first_cdrv_read,

    .write = first_cdrv_write,

    .release = first_cdrv_release,

};

static int __init first_cdrv_init(void)

{

    int ret = 0;

    ret = alloc_chrdev_region(&dev_id, 0, 4, "first_cdrv_one");

    if(ret != 0)

    {

        printk(KERN_ERR"alloc_chrdev_region failed\n");  

    }

    my_cdev = cdev_alloc();

    cdev_init(my_cdev, &fops);

    my_cdev->owner = THIS_MODULE;

    ret = cdev_add(my_cdev, dev_id, 4);

    if(ret != 0)

    {

        printk(KERN_ERR"cdev_add failed\n");  

    }

    first_drv_class = class_create(THIS_MODULE, "first_drv");

    first_drv_class_device = device_create(first_drv_class, NULL, dev_id, NULL, "chenjun");

    

    return 0;

}

static void __exit first_cdrv_exit(void)

{

    device_destroy(first_drv_class, dev_id);

    class_destroy(first_drv_class);

    cdev_del(my_cdev);

    if(my_cdev)

    {

        printk(KERN_ALERT"kzfree\n");

        kzfree(my_cdev);

        my_cdev = NULL;

    }

    unregister_chrdev_region(dev_id, 4);

}

module_init(first_cdrv_init);

module_exit(first_cdrv_exit);

Makefile :

KERNELDIR := /opt/wfe/linux-3.2_m

PWD := $(shell pwd)

#obj-m := hello_world.o

obj-m := first_cdev_module.o

COMPILE_GCC := arm-linux-gcc

TEST := test

TEST_FILE := module_test.c

CLEAN_FILES := *.mod.* *.symvers *.order *.o *.ko $(TEST)

M_CFLAGS := -Os -Wall -g -c

default:

    make -C $(KERNELDIR) M=$(PWD) modules

$(TEST):$(TEST_FILE)

    $(COMPILE_GCC) -o $@ $<

.PHONY:clean

clean:

    rm -rf $(CLEAN_FILES)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: