/*模块注册入口*/
int init_module(void)
{
int result;
dev_t dev = MKDEV(major, 0);
if (major)
{/* 静态注册一个设备,设备号先前指定好,并设定设备名,用cat /proc/devices来查看 */
result = register_chrdev_region(dev, 1, TEST_DEVICE_NAME);
}
else
{
result = alloc_chrdev_region(&dev, 0, 1, TEST_DEVICE_NAME);
}
if (result < 0)
{
printk(KERN_WARNING "Test device: unable to get major %d\n", major);
return result;
}
test_setup_cdev(&test_dev, 0, &test_fops);
printk("The major of the test device is %d\n", major);
return 0;
}
int main()
{
int fd, nwrite, nread;
char buff[BUFF_SZ]; /*缓冲区*/
/* 打开设备文件 */
fd = open(TEST_DEVICE_FILENAME, O_RDWR);
if (fd < 0)
{
perror("open");
exit(1);
}
do
{
printf("Input some words to kernel(enter 'quit' to exit):");
memset(buff, 0, BUFF_SZ);
if (fgets(buff, BUFF_SZ, stdin) == NULL)
{
perror("fgets");
break;
}
buff[strlen(buff) - 1] = '\0';
if (write(fd, buff, strlen(buff)) < 0) /* 向设备写入数据 */
{
perror("write");
break;
}
if (read(fd, buff, BUFF_SZ) < 0) /* 从设备读取数据 */
{
perror("read");
break;
}
else
{
printf("The read string is from kernel:%s\n", buff);
}
} while(strncmp(buff, "quit", 4));
close(fd);
exit(0);
}
4.实验结果
首先在虚拟设备驱动源码目录下编译并加载驱动模块。
$ 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 /* 当卸载设备时打印 */