Embedded LINUX driver learning 4. Character device driver programming (3) Driver registration and uninstallation of user space implementation code
Note: In this example, the generated driver module is the file mychrdev.ko, and all executions are performed on the lower computer
1. Register the driver module:
insmod mychrdev.ko
2. View the registered main device number
cat /proc/devices
Character devices:
1 mem
5 /dev/tty
5 /dev/console
5 /dev/ptmx
........
244 myfile_cdev //主设备号244
........
Three, create a character device file based on the major device number
3.1 Method 1: Created by bash
mknod /dev/mychrdev0 c 244 0
mknod /dev/mychrdev1 c 244 1
mknod /dev/mychrdev2 c 244 2
mknod /dev/mychrdev3 c 244 3
#命令说明:
# Usage: mknod [-m MODE] NAME TYPE MAJOR MINOR
# TYPE:
# b Block device
# c or u Character device
# p Named pipe (MAJOR and MINOR are ignored)
#
Method 2: Create by writing code in C language, see Appendix A for the code, take the compiled file name: mychrdev_reg as an example:
./mychrdev_reg 244 4 mychrdev
#命令说明:
# Usage:comm MAJOR minorct chrdev_name
Four unload the driver module
rmmod mychrdev.ko
Attached A
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc , char * argv[]){
//对命令行输入的参数做判断
if (argc !=4){
printf("参数错误:\n");
printf(" comm <major> <minorct> <name>\n");
return -1;
}
unsigned long int i = 0;
dev_t dev_num;//定义设备号
dev_t major = strtoul(argv[1],NULL,0); 将主设备号转为整数型
int minorct = strtoul(argv[2],NULL,0);//将次设备号数量由字符型转为整形
int path_name_len;
char path_name[128] = "/dev/";//定义初始化保存设备名称的字符数组
char buf[4];//用于保存字符设备名称最后一位,即整形转为字符型的内容
strcat(path_name,argv[3]);//strcat(3)
path_name_len = strlen(path_name);
for(; i<minorct ;i++){
dev_num = makedev(major,i);//见帮忙手册mknod(2) makedev(3)
sprintf(buf,"%d",i);//sprintf(3)
strcat(path_name,buf);//为字符设备名称加编号
mknod(path_name,S_IFCHR,dev_num);//创建字符设备
path_name[path_name_len] = '\0';
}
return 0;
}