当前位置首页 > Linux知识

Linux/dev自动创建设备节点

阅读次数:254 次  来源:admin  发布时间:

#include <linux/module.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/device.h> #include <asm/uaccess.h> #define HELLO_MAJOR 250 #define HELLO_MINOR 0 #define NUMBER_OF_DEVICES 2 struct class *hello_class; static struct cdev cdev; dev_t devno; static ssize_t hello_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { char *str = "hello world"; copy_to_user(buf,str,strlen(str)); *(buf + strlen(str)) = '\n'; return count; } static ssize_t hello_open(struct inode *inode,struct file *file) { return 0; } static const struct file_operations hello_fops = { .open = hello_open, .read = hello_read, .owner = THIS_MODULE, }; static int __init hello_init(void) { int ret; devno = MKDEV(HELLO_MAJOR,HELLO_MINOR); if(HELLO_MAJOR){ ret = register_chrdev_region(devno,NUMBER_OF_DEVICES,"chrdev"); }else{ ret = alloc_chrdev_region(&devno, 0, NUMBER_OF_DEVICES, "chrdev"); } if(ret < 0){ printk("%s register chrdev error\n",__func__); return ret; } hello_class = class_create(THIS_MODULE,"hello_char_calss"); if(IS_ERR(hello_class)){ printk("%s create class error\n",__func__); return -1; } device_create(hello_class, NULL, devno, NULL, "chrdev"); cdev_init(&cdev, &hello_fops); cdev.owner = THIS_MODULE; cdev_add(&cdev, devno, NUMBER_OF_DEVICES); return 0; } static void __exit hello_exit(void) { printk("%s",__func__); cdev_del(&cdev); device_destroy(hello_class,devno); class_destroy(hello_class); unregister_chrdev_region(devno,NUMBER_OF_DEVICES); } module_init(hello_init); module_exit(hello_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("oracleloyal@gmail.com")

Makefile 内容 1 ifeq ($(KERNELRELEASE),)

2 #KERNEL_DIR:=/home/archermind/zhaoxi/bsw_ww02_2016/kernel/cht

3 KERNEL_DIR:=/usr/src/linux-headers-3.13.0-32-generic

4 PWD:=$(shell pwd)

5 modules:

6 $(MAKE) -C $(KERNEL_DIR) M=$(PWD) module

7 modules_install:

8 $(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules_install

9 clean:

10 rm -rf .*.cmd *.ko *.o modules.order Module.symvers *mod.c

11 .PHONY: modules modules_install clea

12 else

13 modules-objs := my.o

14 obj-m := my.o

15 endif

编译模块安装之后会在/sys/class/看到hello_char_class 以及目录内的chrdev,同时也会在/dev下看到udev为我们建立的节点chrdev.

测试程序 #include <stdio.h> #include <fcntl.h> int main(void) { int fd; int i; char buf[50]; fd = open("/dev/chrdev",O_RDWR); if(fd < 0){ printf("can't open dev\n"); return -1; } read(fd,buf,11); printf("%s",buf); return 0; } 测试程序执行后会输出hello world.,
上一篇:Linux-3.14.12内存管理笔记【构建内存管理框架(3)】
下一篇:全网最详细的Windows里Gitclient客户端管理工具SourceTree的下载与安装(图文详解)Git学习系列之Wind