首页 > 解决方案 > 为什么 vfs_write() 添加任意数量的零字节

问题描述

我在嵌入式系统上的内核 2.6.37 上编写一些非常具体的模块驱动程序。我需要将一些数据存储到文件中。因此,当模块“插入”时,我会:

static struct file *filp;
static loff_t pos, mycnt;

static __init int mymodule_init(void) {
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open("/home/mydata.txt", O_WRONLY|O_CREAT, 0644);
set_fs(oldfs);
pos = 0; mycnt=0;
......

然后,在需要时,调用写入数据的函数:

static int mywrite(const char __user *buf, size_t count) {
char str[256]; int i, j;
mm_segment_t oldfs;
int ret;
//Filter out zeroes, if exist
for(i = 0; i < 255; i++) {
    if (i == count) break;
    if (buf[i] == 0) break;
    str[i+1] = buf[i];
}
str[0]=i++;  //Put length in a first byte
//Checking for zeroes ------
for(j = 0; j < i; j++) {
    if (str[j] == 0) {
        printk("0 exist!\n");
        str[j] = 0x02; }
}
//Write 'str' to the file ------
oldfs = get_fs();
set_fs(get_ds());
pos = mycnt;
ret = vfs_write(filp, str, i, &pos);
filp->f_pos = pos;
mycnt += i;
if (mycnt != pos) {
    pos = mycnt;
    vfs_llseek(filp, pos, SEEK_SET);
    printk("Corrected!!!!!!!!!!!!!!!\n"); }
set_fs(oldfs);
//Checking for zeroes again ------
for(j = 0; j < i; j++) {
    if (str[j] == 0)
        printk("0 exist!\n");
}
return count;
}

现在,问题是生成的文件有时包含(罕见的)不应该存在的零块。您可以在编写功能代码中看到特殊代码来检查没有零,只有假定的 ASCII 普通文本。每个字符串的第一个字节也包含它的长度。查看文件,我可以看到它没有计算零。尽管如此,这些零仍然存在。此外,我将 vfs_write 之后的“pos”与预期值进行了比较——它与插入零的次数完全相同(在我的 20KB 文件的测试示例中为 3 次)。而且“更正”不起作用......
那么,我做错了什么?

标签: filelinux-kernelkernel-modulevfs

解决方案


推荐阅读