为什么将 cat 通过管道传输到 chardev 的 head -c 5 会导致对驱动程序读取的调用比仅在 chardev 上调用 head -c 5 多得多?

为什么将 cat 通过管道传输到 chardev 的 head -c 5 会导致对驱动程序读取的调用比仅在 chardev 上调用 head -c 5 多得多?

从中汲取灵感这篇博文,我正在研究Linux设备驱动程序(我正在从中学习)。

read与驱动程序相关的字段被file_operations初始化为以下函数:

static ssize_t mychardev_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
    uint8_t *data = "Hello from the kernel world!\n";
    size_t datalen = strlen(data);

    printk("MYCHARDEV: mychardev_read was called with count equal to %zu\n", count);

    if (count > datalen) {
        count = datalen;
    }

    if (copy_to_user(buf, data, count)) {
        return -EFAULT;
    }

    return count;
}

我的理解是,当用户空间从该驱动程序创建的设备请求给定数量的数据时,传输最多会分批进行datalen,即字符串的长度data,在本例中为 29 (包括尾随的字符串)\n)。在 shell 中执行以下命令可以证实这一点

$ head -c 5 /dev/mychardev-0
$ head -c 29 /dev/mychardev-0
$ head -c 30 /dev/mychardev-0
$ head -c 32 /dev/mychardev-0

结果是输出中的这些行dmesg(假设我在和方法中有明显的printk调用):openrelease

[10782.052736] MYCHARDEV: Device open
[10782.052743] MYCHARDEV: mychardev_read was called with count equal to 5
[10782.052751] MYCHARDEV: Device close
[10868.275577] MYCHARDEV: Device open
[10868.275585] MYCHARDEV: mychardev_read was called with count equal to 29
[10868.275598] MYCHARDEV: Device close
[10878.414433] MYCHARDEV: Device open
[10830.796424] MYCHARDEV: mychardev_read was called with count equal to 30
[10830.796438] MYCHARDEV: mychardev_read was called with count equal to 1
[10830.796443] MYCHARDEV: Device close
[10830.796417] MYCHARDEV: Device open
[10878.414441] MYCHARDEV: mychardev_read was called with count equal to 32
[10878.414455] MYCHARDEV: mychardev_read was called with count equal to 3
[10878.414460] MYCHARDEV: Device close

我不明白的是为什么下面的命令

$ cat /dev/mychardev-0 | head -c 5

结果是

[11186.036107] MYCHARDEV: Device open
[11186.036120] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036131] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036136] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036141] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036145] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036150] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036154] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036159] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036163] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036168] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036172] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036177] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036181] MYCHARDEV: mychardev_read was called with count equal to 8192
[11186.036187] MYCHARDEV: Device close

原则上,我理解,也许是一次批量地从驱动程序cat请求(或者我应该说 shell 运行时?或者什么?)数据(在本例中是 8192,显然),而不是逐字节请求cat-byte,为了提高性能。

但我不明白为什么要调用这么多次?

相关内容