Linux驱动应用-以misc为例

Linux  ·  2025-08-22

在前面,我们已经实现了一个驱动,下面就可以写一个程序来使用一下这个驱动

1.概念回顾

之前的介绍中,我们提到了一个驱动的全部使用生命周期

  • 设备结构体->实现file_operations的文件读、写、打开、关闭函数->给出模块入口出口函数
  • 内核或者用户手动加载驱动->进入模块入口,注册设备结构体,在/dev下新增设备接口
  • 用户的APP启动

          -> 打开设备接口   -> 通过设备结构体的file_operations调用misc_open
          -> 向设备写入数据 -> 通过设备结构体的file_operations调用misc_write
          -> 读设备的数据   -> 通过设备结构体的file_operations调用misc_read
          -> 关闭设备       -> 进入模块出口,释放设备结构体,调用misc_release
    

2.流程分析

  • 在这里,我们就要实现用户启动后的动作,辅以查看log,上面的设备驱动调用分析是否正确
    首先程序我们先打开设备,驱动会打印misc open
    然后读取设备的数据,设备驱动里我们给了默认值abcde,所以我们会读取到abcde
    再向设备写入了12345,驱动会在控制台打印write:12345
    最后我们关闭了设备,设备会注销并打印misc release

通过这个流程的实现,相信Linux驱动的大致框架会在脑海里有一个初步的概念

编译程序:aarch64-linux-gnu-gcc APP.c -o app
将app文件拷贝到开发板上执行即可

APP.C

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

int main(int argc, char * argv[]){
    
    int fd;
    char buf[64] = {0};
    fd = open("/dev/MISC_TEST",O_RDWR);
    if(fd < 0){
        perror("open error\n");
        return fd;
    }
    
    read(fd, &buf, sizeof(buf));
    printf("buf %s\n",buf);
    
    char buf1[64] = "12345";
    write(fd, &buf1, strlen(buf1));
        
    close(fd);
    
    return 0;
}
 驱动
评论
LJ` Blog . All Rights Reserved. Theme Jasmine by Kent Liao.
冀ICP备2025127925号 冀公网安备13082402000074号