主题 : 關於driver /sys/class/hello建立 复制链接 | 浏览器收藏 | 打印
级别: 侠客
UID: 113147
精华: 0
发帖: 107
金钱: 535 两
威望: 107 点
贡献值: 0 点
综合积分: 214 分
注册时间: 2015-03-05
最后登录: 2015-09-16
楼主  发表于: 2015-03-17 13:06

 關於driver /sys/class/hello建立

可否幫忙看看為何insmod執行後tree /sys/class, 並沒有hello device產生

hello.c
#include <linux/device.h>  
#include <linux/module.h>  
#include <linux/kernel.h>  
#include <linux/init.h>  
#include <linux/cdev.h>  
#include <linux/fs.h>  

MODULE_LICENSE("Dual BSD/GPL");

#define DEVNAME "hello"  
static dev_t dev;  
static struct class *hello_class;  
static struct cdev *hello_cdev;  
int hello_major = 250;
        int hello_minor = 0;
  
static int hello_open(struct inode *inode,struct file *flp)  
{  
    return 0;  
}  
  
static int hello_close(struct inode *inode,struct file *flp)  
{  
        return 0;  
}  
static struct file_operations hello_fops={  
        .owner=THIS_MODULE,  
        .open   =hello_open,  
        .release=hello_close,  
};  

static int __init hello_init(void)
{
    //int error;

    //error = alloc_chrdev_region(&dev, 0, 2, "hello");
    int error, dev = MKDEV (hello_major, hello_minor);
    if (error)
    {
        printk("hello: alloc_chardev_region failed!\n");
        goto out;
    }
    hello_cdev = cdev_alloc();
    if (hello_cdev == NULL)
    {
        printk("hello: alloc cdev failed!\n");
        error = -ENOMEM;
        goto out_chrdev;
    }
    hello_cdev->ops = &hello_fops;
    hello_cdev->owner = THIS_MODULE;
    error = cdev_add(hello_cdev, dev, 1);
    if (error)
    {
        printk("hello: cdev_add failed!\n");
        goto out_cdev;
    }
    hello_class = class_create(THIS_MODULE, DEVNAME);
    if (IS_ERR(hello_class))
    {
        error = PTR_ERR(hello_class);
        goto out_chrdev;
    }
    device_create(hello_class, NULL, dev , NULL, DEVNAME);
    //memset (hello_buf, 0, sizeof(hello_buf));
    //memcpy(hello_buf, DEFAULT_MSG, sizeof(DEFAULT_MSG));
    printk("hello: Hello World!\n");
    return 0;

out_cdev:
    cdev_del(hello_cdev);
out_chrdev:
    unregister_chrdev_region(hello_cdev->dev, 2);
out:
    return error;
}
static void __exit hello_exit(void)
{
    device_destroy(hello_class, dev);
    class_destroy(hello_class);
    unregister_chrdev_region(hello_cdev->dev, 2);
    cdev_del(hello_cdev);
    printk("hello: Goodbye World\n");
}

Makefile

#
# Makefile for kernel test
#
PWD         := $(shell pwd)
KVERSION    := $(shell uname -r)
KERNEL_DIR   = /usr/src/linux-headers-$(KVERSION)/
MODULE_NAME  = hello
obj-m       := $(MODULE_NAME).o  
all:
    make -C $(KERNEL_DIR) M=$(PWD) modules
clean:
    make -C $(KERNEL_DIR) M=$(PWD) clean


级别: 侠客
UID: 113147
精华: 0
发帖: 107
金钱: 535 两
威望: 107 点
贡献值: 0 点
综合积分: 214 分
注册时间: 2015-03-05
最后登录: 2015-09-16
1楼  发表于: 2015-03-18 13:11
model_init(), model_exit()忘了加= ="