您好,我正在编写一个字符驱动程序,用于读取和写入特定设备。因为我是菜鸟,所以这是一个非常简单易用的字符驱动器,它只使用最简单的协议(protocol),如打开、读取、写入和释放。为了测试我的驱动程序,我正在使用以下程序……下面是我的用户空间程序的源代码。
#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() 仅在我关闭文件描述符时写入,最糟糕的是,在我从我的设备读取后执行。当然,我想写入我的设备然后从中读取,但这并没有发生。这给我的印象是用户空间中的许多事情同时执行,这让我感到困惑。在处理用户空间时,我如何知道调用设备函数的顺序。抱歉,如果这看起来含糊不清,我会详细说明任何模糊的地方。
感谢您的任何回复!
最佳答案
您对“fd”的写入被缓存,并且仅在您关闭它后写入设备驱动程序。 这是正常的,这样做是为了减少系统调用的数量。
如果您确实需要将每次写入都发送到设备,请尝试在每次写入后添加对 fsync() 的调用。 或者,由于它是一个字符驱动程序,它很可能是行缓冲的,请尝试在每行末尾添加一个“\n”。
关于c - 用户空间代码以什么顺序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9883861/