hello 驱动模块

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fcntl.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>

#define    DEVICE_NAME  "hello" 
#define    HELLO_MAJOR 249

static int hello_major = HELLO_MAJOR;
static struct cdev hello_dev;

MODULE_LICENSE("GPL");
static int  hello_open(struct inode *inode, struct file *file)
{
    return 0;
}


static int  hello_release(struct inode *inode, struct file *file)
{
    return 0;
}


static ssize_t hello_read(struct file *file, char  *buf, size_t cnt, loff_t *offset)
{
	return 0;
}


static ssize_t hello_write(struct file *file, const char *buf, size_t cnt, loff_t *offset)
{
	return 0;
}

static int  hello_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	return 0;
}

static struct file_operations hello_fops = {
    .owner      =      THIS_MODULE,
    .read       =      hello_read,
    .write      =      hello_write,      
    .release    =      hello_release,
    .open	=      hello_open,
    .ioctl      =      hello_ioctl,  // 新版本内核使用 .unlocked_ioctl = 
};

static int __init my_hello_module_init(void)
{
	int res = -1;
	int err;
	dev_t dev = MKDEV(hello_major,0);
	if(hello_major)
		res = register_chrdev_region(dev,1,DEVICE_NAME);
	else{
		res = alloc_chrdev_region(&dev,0,1,DEVICE_NAME);
	}
	if(res < 0)
	{
		printk("Can't allocate major number for hello device\r\n");
		return res;
	}
	memset(&hello_dev,0,sizeof(hello_dev));
	
	/*初始化并添加cdev结构体*/	
	cdev_init(&hello_dev,&hello_fops);
	hello_dev.owner = THIS_MODULE;
	hello_dev.ops	= &hello_fops;
	err = cdev_add(&hello_dev,dev,1);	
	if(err){
		printk("Add hello device error %d\n",err);
	}
	printk("Hello, my module is installed !\n");
	return 0;
}
static void __exit my_hello_module_cleanup(void)
{
	    dev_t dev;

	    cdev_del(&hello_dev);
   	    dev = MKDEV(hello_major, 0);
   	    unregister_chrdev_region(dev, 1);

	
	printk("Good-bye, my module was removed!\n");
}
module_init(my_hello_module_init);
module_exit(my_hello_module_cleanup);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值