3.用户程序与驱动交互

驱动程序请使用第二章https://blog.csdn.net/chenhequanlalala/article/details/140034424

用户app与驱动交互最常见的做法是insmod驱动后,生成一个设备节点,app通过open,read等系统调用去操作这个设备节点,这里先用mknode命令调试。

mknod 设备名 设备类型(b块设备/c字符设备/p管道) 主设备号 次设备号

mknod /dev/hello c 240 0

使用mknode后生成了/dev/hello节点,写入数据到hello节点中,查看dmesg的输出发现调用了驱动的open write release

echo 1 > /dev/hello
802.771723 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_open 48

802.773196 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_write 40

802.773285 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_release 56

这里写一个C程序来读写这个设备节点

复制代码
#include "linux/string.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

/*
读数据 ./hello_test xxx(设备节点名字)
写数据 ./hello_test xxx(设备节点名字) string
*/

int main(int argc, char **argv)
{
    int fd;
    int len;
    char buf[1024];

    if(argc < 2)
    {
        printf("Usage :\n");
        printf("%s <dev> [str]\n", argv[0]);
        return -1;
    }

    //open
    fd = open(argv[1], O_RDWR);
    if(fd < 0)
    {
        printf("open %s failed\n", argv[1]);
        return -1;
    }

    //read
    if(argc == 2)
    {
        len = read(fd, buf, sizeof(buf));
        printf("%s\n", buf);
    }
    //write
    else if(argc == 3)
    {
        len = write(fd, argv[2], strlen(argv[2]));
    }
    else
    {
        printf("Too many parameters\n");
    }

    close(fd);
}

分别调用 ./hello_test /dev/hello 123 和 ./hello_test /dev/hello 后,查看dmesg输出显示

2770.434595 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_open 48

2770.434664 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_write 40

2770.434705 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_release 56

2772.388372 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_open 48

2772.388439 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_read 32

2772.389257 /home/book/nfs_rootfs/drivers_projects/01_hello_drv/hello_drv.c hello_release 56

app的open write read release都一一对应上了。

这里的./hello_test /dev/hello其实没有读到数据,打印如下,原因下一章再说。

root@100ask:/mnt/drivers_projects/01_hello_drv# ./hello_test /dev/hello

read size = 1024 data =

相关推荐
正仪8 分钟前
systemd 是什么?
linux·运维·windows
暖核10 分钟前
华为云运维三件套实战:云审计 + 云监控 + 云日志完整操作指南
linux·运维·华为云
AI+程序员在路上41 分钟前
Rv1126b与手机(SPP蓝牙串口APP)蓝牙通信流程
linux·c语言·智能手机
虚无的纽扣1 小时前
【Linux】进程第二课:进程优先级和环境变量
linux·运维·服务器
maosheng11461 小时前
【无标题】linux中企业容易考的的小知识点1(rhcsa)
linux·运维·服务器
牢姐与蒯1 小时前
Linux进程(九).自定义shell——深度理解命令行和shell
linux·运维·服务器
天道jimmy1 小时前
VulnHub 系列:View2aKill,1
linux·运维·服务器
mengge.cloud2 小时前
0909华为云网络类服务实践小白实验教程
linux·运维·服务器·网络·华为云·php
小诗懂技术2 小时前
从零手写一个 C 语言 HTTP 商品查询服务器:全链路技术实践
linux·服务器·网络
Escalating_xu2 小时前
【Linux mmap 文件映射】从虚拟地址到页缓存:读写文件、匿名映射与极简 malloc
linux·缓存