在上一篇文章中学习了linux字符驱动的开发,需要使用应用程序对完成的驱动进行验证,现在开始学习应用程序的开发。
一、准备材料
开发环境:VMware
操作系统:ubuntu
开发版:湃兔i2S-6UB
二、man手册使用
学过编程语言的小伙伴都知道在使用一些函数的时候需要导入相应的库文件,而函数属于哪个图文件都会也相应的API说明文档,而linux开发也不例外。在linux系统中提供了man手册,比如我需要查询printf()这个函数所在的头文件是那个,只需要linux下使用man 3 printf
命令即可查看,如下图所示
当你不知道使用的函数需要应用什么头文件时即可通过man手册进行查询,具体教程可以参考Linux Man手册的使用示例。
三、main参数
在学习c语言的时候,使用的main的函数都是int main(void)
,而在linux却多了两个变量,原型如下所示
int main(int argc, char *argv[]) {
return 0;
}
argc:应用程序参数个数
argv[]:具体的参数内容,字符串形式
如果在linux下这样./helloApp 1
执行程序时,那么程序中argc = 1 、 argv[0] = 1
。可以通过这样的形式将执行用户需要的变量传入函数中。
四、程序编写
linux对调用驱动程序时都是通过文件的形式进行操作的,所谓的linux下一切皆文件,需要用到以下函数
int open(const char *pathname, int flags)
int close(int fd)
ssize_t write (int fd, const void * buf, size_t count)
ssize_t read(int fd, void * buf, size_t count)
需要了解函数相应是使用方法,可以通过man手册进行查询,准备工作完成后就可以开始应用程序的编写了。
源码hello2.c文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
/*
*argc:应用程序参数个数
*argv[]:具体的参数内容,字符串形式
*./hello2App <filename> <1:2> 1表示读,2表示写
*./hello2App /dev/hello2 1 表示从驱动里面读数据
*./hello2App /dev/hello2 2 表示向驱动里面写数据
* */
int main(int argc, char *argv[])
{
int ret = 0;
int fd = 0;
char *filename;
char readbuf[100], writebuf[100];
static char usrdata[] = {"hell0 This is user data!"};
if(argc !=3) {
printf("Instruction usage error!!!\r\n");
printf("./helle2App <filename> <1:2> 1表示读,2表示写\r\n");
printf("./hello2App ./dev/hello2 1 \r\n");
return -1;
}
filename = argv[1];
fd = open(filename, O_RDWR);
if(fd < 0) {
}
if(atoi(argv[2]) ==1){
ret = read(fd, readbuf, 50);
if(ret <0) {
printf("read file %s failed!\r\n", filename);
} else {
printf("App read data:%s\r\n", readbuf);
}
}
if(atoi(argv[2]) == 2) {
memcpy(writebuf, usrdata, sizeof(usrdata));
ret = write(fd,writebuf, 50);
if(ret <0) {
printf("write file %s failed\r\n", filename);
} else {
}
}
ret =close(fd);
if(ret <0) {
printf("close file %s falied!\r\n", filename);
}
return 0;
}
代码编写完成后使用交叉编译器编译,编译完成后将驱动和应用程序都拷贝至arm开发板的/lib/modules/4.1.43+目录下
arm-linux-gnueabihf-gcc hello2App.c -o hello2App
sudo cp hello2App hello2_demo2.ko /home/rootfs/lib/modules/4.1.43+ -f
五、测试
启动开发板,进入/lib/modules/4.1.43+目录,然后加载之前编写的驱动
modprobe hello_demo2
lsmod
cat /proc/devices
创建属性节点
mknod /dev/helle2 c 248 0
ls /dev
创建成功后/dev目录下回生成一个hello2的文件,然后运行应用程序对驱动进行测试
./hello2App /dev/hello2 1
./hello2App /dev/hello2 2
看到如图信息说明我们编写的应用程序和驱动都是成功的,测试完成后卸载驱动即可。
rmmod hello_demo2
参考文献
Linux Man手册的使用示例:https://www.cnblogs.com/shanyu20/p/10943393.html
linux open函数详解:https://blog.csdn.net/renlonggg/article/details/80701949
深入理解linux下write()和read()函数:https://blog.csdn.net/boiled_water123/article/details/81951351
正点原子视屏教程:https://www.bilibili.com/video/BV1fJ411i7PB?p=6