嗨,我正在编写一个读取和写入特定设备的字符驱动程序。由于我是菜鸟,这是一个非常简单易用的字符驱动器,它只使用最简单的协议,例如打开、读取、写入和释放。为了测试我的驱动程序,我使用了以下程序……下面是我的用户空间程序的源代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <poll.h>
int main(void){
int num;
char *buff;
FILE *fd = fopen("/dev/hi","a+");
num = fprintf(fd,"this is sentence 1 !!");
num = fprintf(fd,"this is sentence 2 !!");
num = fprintf(fd,"this is sentence 3 !!");
num = fprintf(fd,"this is sentence 4 !!");
num = fprintf(fd,"this is sentence 5 !!");
buff = malloc(sizeof(char) * num+1);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
free(buff);
close(fd);
return 0;
}
现在,我的驱动程序如何工作并不重要,但我调用读写方法的顺序是什么。理想情况下,如果按照我编写代码的顺序写入驱动程序并按照我编写代码的顺序读取驱动程序,那就太好了。但是我注意到,如果我编写了我的代码,比如......
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <poll.h>
int main(void){
int num;
char *buff;
FILE *fd = fopen("/dev/hi","w");
num = fprintf(fd,"this is sentence 1 !!");
num = fprintf(fd,"this is sentence 2 !!");
num = fprintf(fd,"this is sentence 3 !!");
num = fprintf(fd,"this is sentence 4 !!");
num = fprintf(fd,"this is sentence 5 !!");
close(fd);
fd = fopen("/dev/hi","r");
buff = malloc(sizeof(char) * num+1);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
fread(buff,sizeof(char),num+1,fd);
printf("%s\n",buff);
free(buff);
close(fd);
return 0;
}
我注意到 fprintf() 仅在我关闭文件描述符时写入,最糟糕的是,在我从设备读取后执行。当然,我想写入我的设备,然后从中读取,但这并不是按顺序发生的。这给我的印象是用户空间中的许多事情同时执行,这让我感到困惑。在处理用户空间时,我如何知道我的设备函数被调用的顺序。抱歉,如果这看起来含糊不清,我会详细说明任何模糊不清的地方。
感谢您的任何回复!