endif
(3)加载和卸载模块。 通过下面两个脚本代码分别实现驱动模块的加载和卸载。 加载脚本 test_drv_load 如下所示:
#!/bin/sh # 驱动模块名称
module=\
# 设备名称。在/proc/devices 中出现 device=\# 设备文件的属性 mode=\group=\
# 删除已存在的设备节点 rm -f /dev/${device} # 加载驱动模块
/sbin/insmod -f ./$module.ko $* || exit 1 # 查到创建设备的主设备号
major=`cat /proc/devices | awk \# 创建设备文件节点
mknod /dev/${device} c $major 0 # 设置设备文件属性
chgrp $group /dev/${device} chmod $mode /dev/${device}
卸载脚本 test_drv_unload 如下所示:
#!/bin/sh
module=\device=\# 卸载驱动模块
/sbin/rmmod $module $* || exit 1 # 删除设备文件
rm -f /dev/${device} exit 0
(4)编写测试代码。
最后一步是编写测试代码,也就是用户空间的程序,该程序调用设备驱动来测试驱动的运行是否正常。以下实例只实现了简单的读写功能,测试代码如下所示:
/* test.c */ #include
11
#include
#define TEST_DEVICE_FILENAME \设备文件名*/ #define BUFF_SZ 1024 /* 缓冲大小*/ int main() {
int fd, nwrite, nread; char buff[BUFF_SZ]; /* 打开设备文件 */
fd = open(TEST_DEVICE_FILENAME, O_RDWR); if (fd < 0) {
perror(\exit(1); } do {
printf(\memset(buff, 0, BUFF_SZ);
if (fgets(buff, BUFF_SZ, stdin) == NULL) {
perror(\break; }
buff[strlen(buff) - 1] = '\\0';
if (write(fd, buff, strlen(buff)) < 0) /* 向设备写入数据 */ {
perror(\break; }
if (read(fd, buff, BUFF_SZ) < 0) {
perror(\break; } else {
/*缓冲区*/
/* 从设备读取数据 */
printf(\
}
} while(strncmp(buff, \close(fd); exit(0); }
12
四、实验结果
首先在虚拟设备驱动源码目录下编译并加载驱动模块。
$ make clean;make $ ./test_drv_load
接下来,编译并运行测试程序
$ gcc –o test test.c $ ./test
测试程序运行效果如下:
Input some words to kernel(enter 'quit' to exit):Hello, everybody! The read string is from kernel:Hello, everybody! /* 从内核读取的数据 */ Input some words to kernel(enter 'quit' to exit):This is a simple driver The read string is from kernel: This is a simple driver Input some words to kernel(enter 'quit' to exit):quit The read string is from kernel:quit
最后,卸载驱动程序
$ ./test_drv_unload
通过 dmesg 命令可以查看内核打印的信息:
$ dmesg|tail –n 10 ……
The major of the test device is 250 /* 当加载模块时打印 */ This is open operation This is release operation Test device uninstalled
/* 当打开设备时打印 */ /* 关闭设备时打印 */ /* 当卸载设备时打印 */
13