为什么在Linux字符驱动程序读取调用中大小总是= 4096?

我一直在通过网络上的 Linux char驱动程序示例工作,但遇到了我无法解释的行为.
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;
}

该消息始终指示cnt = 4096字节,无论用户空间调用中指定的字节数是多少(例如…

[11043.021789] Read called for 4096 bytes

但是,用户空间读取调用

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).

我相信第一次调用fread()5个字节时,libc会执行4096字节的内部read(),而后面的fread()将只返回与您使用的FILE结构相关联的缓冲区中已有的libc字节.直到达到4096.第4097个字节将发出另一个4096字节的读取,依此类推.

当你编写时也会发生这种情况,例如当使用printf()时,它只是带有stdout()的fprintf()作为它的第一个参数. 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;
}

我从来没有尝试过,但我猜你可以用FILE *来做同样的事情,当fopen()你的角色设备并禁用I / O缓冲时:

FILE* fh = fopen("/dev/my-char-device","rb");
setvbuf(fh,0);

相关文章

1、安装Apache。 1)执行如下命令,安装Apache服务及其扩展包...
一、先说一下用ansible批量采集机器信息的实现办法: 1、先把...
安装配置 1. 安装vsftpd 检查是否安装了vsftpd # rpm -qa | ...
如何抑制stable_secret读取关键的“net.ipv6.conf.all.stabl...
1 删除0字节文件 find -type f -size 0 -exec rm -rf {} ...
## 步骤 1:安装必要的软件包 首先,需要确保系统已安装 `dh...