09_编写简单的应用程序调用驱动
9.1 目标
• 编写简单应用调用驱动
– 调用HELLO_CTL123设备节点
9.2 头文件
• 打印头文件
– include <stdio.h>调用打印函数printf
• 应用中调用文件需要的头文件
– #include <sys/types.h>基本系统数据类型。系统的基本数据类型在 32 编译环境中保持为 32 位值,并会在 64 编译环境中增长为 64 位值。
– #include <sys/stat.h>系统调用函数头文件。可以调用普通文件,目录,管道,socket,字符,块的属性
– #include <fcntl.h>定义了open函数
– #include <unistd.h>定义了close函数
– #include <sys/ioctl.h>定义了ioctl函数
• 调用的头文件是和编译器放在一起的
– 这里使用arm2009q3编译器,编译器使用arm-none-linux-gnueabi-gcc
• 在编译器目录下使用查找命令找到该头文件
– 例如#find ./ -name types.h
9.3 编写简单的应用程序
• 调用的函数
– open函数是返回文件描述符
– ioctl函数是应用向驱动传值
– close函数是关闭打开的文件
• 编写应用程序的代码,编译
– arm-none-linux-gnueabi-gcc -o invoke_hello invoke_hello.c -static
代码程序:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
main(){
int fd;
char *hello_node = "/dev/hello_ctl123";
/*O_RDWR只读打开,O_NDELAY非阻塞方式*/
if((fd = open(hello_node,O_RDWR|O_NDELAY))<0){
printf("APP open %s failed",hello_node);
}
else{
printf("APP open %s success",hello_node);
ioctl(fd,1,6);
}
close(fd);
}
• 开发板中加载devicenode_linux_module驱动,运行应用
运行后提示报错:Segmentation fault

...

原因分析:驱动程序中.unlocked_ioctl赋值为1是错误的,需要改正为:.unlocked_ioctl =hello_ioctl
static struct file_operations hello_ops = {
.owner = THIS_MODULE,
.open = hello_open,
.release = hello_release,
.unlocked_ioctl =1,
};
改正后,编译结果如下:

本文介绍如何通过编写简易应用程序来调用设备驱动,包括必要的头文件包含、函数使用及常见错误排查,如驱动程序中.unlocked_ioctl的正确设置。

被折叠的 条评论
为什么被折叠?



