[国嵌攻略][112][使用字符设备驱动]

编译/安装驱动程序

在Linux系统中,驱动程序通常采用内核模块的程序结构来进行编码。因此编译/安装一个驱动程序,其实就是编译/安装一个内核模块。

示例:

make

insmod memdev.ko

创建设备文件

应用程序->设备文件->驱动程序

通过字符设备文件,应用程序可以使用相应的字符设备驱动程序来控制字符设备。创建字符设备文件的方法一般有两种:

1.使用mknod命令

mknod /dev/文件名 c 主设备号 次设备号

驱动程序通过主设备号与字符设备文件一一对应,驱动程序的主设备号可以同过cat /proc/devices来查看,次设备号取非负数。c表示是字符设备。

2.使用函数在驱动程序中创建。

示例:

mknod /dev/memdev0 c 253 0

应用程序编写

arm-linux-gcc –static write.c –o write

arm-linux-gcc –static read.c –o read

Makefile

obj-m := memdev.o
KDIR := /space/work/guoqian/liunxkernel/000/kernel/linux-mini2440

all :
    make -C $(KDIR) M=$(PWD) modules ARCH=arm CROSS_COMPILE=arm-linux-
    
clean :
    @rm -f *.o *.ko *.mod.* *.order *.symvers

write.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv){
    //打开设备文件
    int fd;
    
    fd = open("/dev/memdev0", O_RDWR);
    
    //写入数据
    int num;
    
    num = 2016;
    write(fd, &num, sizeof(num));
    
    //关闭设备文件
    close(fd);
    
    return 0;
}

read.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv){
    //打开设备文件
    int fd;
    
    fd = open("/dev/memdev0", O_RDWR);
    
    //读取数据
    int num;
    
    read(fd, &num, sizeof(num));
    printf("num is %d
", num);
    
    //关闭设备文件
    close(fd);
    
    return 0;
}
原文地址:https://www.cnblogs.com/d442130165/p/5248306.html