register_chrdev函数简单使用

register_chrdev函数网上介绍的文章比较多,就不概述了。

以下是例子。

#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/fs.h>
#include<linux/slab.h>
#include<linux/timer.h>
#include<linux/sched.h>
#include<linux/list.h>
#include<linux/interrupt.h>
#include<linux/cdev.h> //cdev_init() cdev_add() cdev_del()
#include<linux/types.h> //dev_t
#include<linux/kdev_t.h> //有两个宏获取主设备号和次设备号

#include<linux/uaccess.h> //container_of
MODULE_AUTHOR("Tan xujia");
MODULE_LICENSE("Dual BSD/GPL");

/*设备的操作方法*/
int
char_open(struct inode *inode, struct file *filp)
{
		printk("open\n");
    	return 0;
}

ssize_t
char_read(struct file *filp, char __user *buf, size_t count, loff_t *fpos)
{
		printk("read\n");
    	return 0;
}

ssize_t
char_write(struct file *filp, const char __user *buf, size_t count, loff_t *fpos)
{
		printk("write\n");
    	return 1;
}

int
char_release(struct inode *inode, struct file *filp)
{
    printk("release\n");
    return 0;
}

struct file_operations char_fops = {
    .owner = THIS_MODULE,
    .read = char_read,
    .write = char_write,
    .open = char_open,
    .release = char_release,
};

int megasas_mgmt_majorno;
static
int __init hello_init (void)
{
	int rval = register_chrdev(0, "megaraid_sas_ioctl", &char_fops);

	if (rval < 0) {
		printk(KERN_DEBUG "megasas: failed to open device node\n");
		return rval;
	}
	megasas_mgmt_majorno = rval; //返回值是主设备号
	printk("rval = %d\n", rval);
	return 0;
}

static
void __exit hello_exit (void)
{
	unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
}

module_init(hello_init);
module_exit(hello_exit);

makefile:

在这里插入代码片

在/proc目录下,cat device时可以看到该megaraid_sas_ioctl字符设备的设备号,但是由于该设备文件还没有设备节点,所以还无法执行到对应的read等回调函数,所以可以利用函数或者mknod命令创建相应的设备节点,比如,

mknod /dev/mega c 234 0

然后就可以对mega进行cat,echo了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值