课堂实践4:
• 参照“实践 3 ”的测试程序,编写 memory-26.c 的测试程序 test-memory-26.c ,不必使用多线程。测试包括写入数据和读取数据 , 正如 《 Linux 设备驱动开发入门 ( 中文版 ). pdf 》 P18 页 内的测试方法一样,如果写入多个字符,则实际写入最后一个,例如写入“ abc ” ,则实际写入“ c ”。
gets() 函数不安全。。。
• 参照“实践 3 ”的测试程序,编写 memory-26.c 的测试程序 test-memory-26.c ,不必使用多线程。测试包括写入数据和读取数据 , 正如 《 Linux 设备驱动开发入门 ( 中文版 ). pdf 》 P18 页 内的测试方法一样,如果写入多个字符,则实际写入最后一个,例如写入“ abc ” ,则实际写入“ c ”。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> //UNIX标准函数定义
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> //文件控制定义
#include <termios.h> //PPSIX终端控制定义
#include <errno.h> //错误号定义
#include <pthread.h>
int main()
{
char p[20] = {0};
char tmp[20] = {0};
int ret = 0;
int memoryfd;
//打开memory设备
if ((memoryfd = open("/dev/my_memory", O_RDWR|O_NONBLOCK)) < 0) {
printf("cannot open the memory device\n");
exit(0);
}
while (1) {
printf("Input(quit is exit):");
gets(p); //获取输入
/*
if (!(fgets(p, 20, stdin))) {
exit(0);
}
*/
//quit退出
if (strcmp(p, "quit") == 0)
exit(0);
//写入数据
if ((ret = write(memoryfd, p, strlen(p))) < 0) {
printf("write fall!\n");
exit(0);
}
printf("reading...\n");
sleep(1);
//读取数据
if ((ret = read(memoryfd, tmp, sizeof(char))) < 0) {
printf("read fall!\n");
exit(0);
}
printf("\nOutput:%s\n\n", tmp);
}
return 0;
}
gets() 函数不安全。。。