我一直在研究网络上的 Linux 字符驱动程序示例,但遇到了我无法解释的行为。
static ssize_t my_read(struct file *f, char __user *user_buf, size_t cnt, loff_t* off)
{
printk( KERN_INFO "Read called for %zd bytes\n", cnt );
return cnt;
}
无论用户空间调用读取的字节数是多少(例如..
[11043.021789] Read called for 4096 bytes
但是,用户空间的read调用
retval = fread(_rx_buffer, sizeof(char), 5, file_ptr);
printf( "fread returned %d bytes\n", retval );
用户空间的输出是
fread returned 5 bytes.
为什么 my_read
中的大小值总是 4096 而 fread
中的值却指示 5 ?我知道我缺少一些东西,但不确定是什么......
最佳答案
尝试 read(2)
(在 unistd.h
中)它应该输出 5 个字符。使用 libc(fread(3)
、fwrite(3)
等)时,您使用的是内部 libc 缓冲区,它通常是一个页面的大小(几乎总是 4 kiB)。
我相信你第一次为 5 个字节调用 fread()
时,libc 会执行一个 4096 字节的内部 read()
和下面的 fread( )
将简单地返回 libc 已经在与您使用的 FILE
结构关联的缓冲区中的字节。直到达到 4096。第 4097 个字节将发出另一个 read
4096 字节等等。
这也会发生在你写的时候,例如当使用 printf()
时,它只是 fprintf()
和 stdout()
作为它的第一个参数。 libc 不会直接调用 write(2)
,而是将您的内容放入其内部缓冲区(也是 4096 字节)。如果你调用它会刷新
fflush(stdout);
您自己,或任何时候它在发送的字节中找到字节 0x0a(ASCII 中的换行符)。
试试吧,你会看到:
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for sleep() */
int main(void) {
printf("the following message won't show up\n");
printf("hello, world!");
sleep(3);
printf("\nuntil now...\n");
return 0;
}
但这会起作用(不使用 libc 的缓冲):
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for sleep(), write(), and STDOUT_FILENO */
int main(void) {
printf("the following message WILL show up\n");
write(STDOUT_FILENO, "hello!", 6);
sleep(3);
printf("see?\n");
return 0;
}
STDOUT_FILENO
是标准输出 (1) 的默认文件描述符。
每次出现换行符时刷新对于终端用户即时看到消息是必不可少的,也有助于逐行处理,这在 Unix 环境中经常进行。
因此,即使 libc 使用 read()
和 write()
系统调用直接填充和刷新其缓冲区(顺便说一下,C 标准的 Microsoft 实现库必须使用 Windows 的东西,可能是 ReadFile
和 WriteFile
),那些系统调用绝对不知道 libc。当同时使用两者时,这会导致有趣的行为:
#include <stdio.h> /* for printf() */
#include <unistd.h> /* for write() and STDOUT_FILENO */
int main(void) {
printf("1. first message (flushed now)\n");
printf("2. second message (without flushing)");
write(STDOUT_FILENO, "3. third message (flushed now)", 30);
printf("\n");
return 0;
}
哪些输出:
1. first message (flushed now)
3. third message (flushed now)2. second message (without flushing)
(第三个在第二个之前!)。
另请注意,您可以使用 setvbuf(3)
关闭 libc 的缓冲.示例:
#include <stdio.h> /* for setvbuf() and printf() */
#include <unistd.h> /* for sleep() */
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
printf("the following message WILL show up\n");
printf("hello!");
sleep(3);
printf("see?\n");
return 0;
}
我从未尝试过,但我猜你可以对 fopen()
字符设备时得到的 FILE*
做同样的事情,并禁用 I/O 缓冲这个:
FILE* fh = fopen("/dev/my-char-device", "rb");
setvbuf(fh, NULL, _IONBF, 0);
关于c - 为什么在 Linux 字符驱动读取调用中 size 总是 = 4096?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867102/