buptldf 发表于 2013-10-21 09:52

请教一个内核写文件的问题

最近在写一段内核里写文件的代码,遇到一些问题。
就是网上找到的最简单的一段内核写文件的代码,修改了一下。
本意是,传入8KB的Buffer,写到文件后文件大小为80KB,内容依次为0x0,0x1。。。0x9。
执行这段代码后,生成的文件只有8KB,内容是0x9,也就是10次都写在文件开始的8KB上了。
在write前后将filp->f_pos和文件大小都打印出来了,确实是按照8KB大小在递增。
网上查了很多资料,也不得要领,llseek什么的也都试过,效果都一样,请有经验的朋友给些意见。先谢谢了。

static void filewrite(char* filename, char* data, u32 data_len)
{
struct file *filp;
mm_segment_t fs;
u32 index = 0;

filp = filp_open(filename, O_RDWR| O_APPEND| O_CREAT, 0644);
if(IS_ERR(filp))
{
      printk("open error...\n");
      return;
}
fs=get_fs();
set_fs(KERNEL_DS);

for(index = 0; index < 10; index++)
{
    memset(data, index, data_len);
    filp->f_op->write(filp, data, strlen(data),&filp->f_pos);
}
set_fs(fs);
filp_close(filp,NULL);
}

每次write前后打印的f_pos和文件大小:
Oct 21 17:31:20 localhost kernel: filp->f_pos1 0 len 0
Oct 21 17:31:20 localhost kernel: filp->f_pos2 8192 len 8192
Oct 21 17:31:20 localhost kernel: filp->f_pos1 8192 len 8192
Oct 21 17:31:20 localhost kernel: filp->f_pos2 16384 len 16384
Oct 21 17:31:20 localhost kernel: filp->f_pos1 16384 len 16384
Oct 21 17:31:20 localhost kernel: filp->f_pos2 24576 len 24576
Oct 21 17:31:20 localhost kernel: filp->f_pos1 24576 len 24576
Oct 21 17:31:20 localhost kernel: filp->f_pos2 32768 len 32768
Oct 21 17:31:20 localhost kernel: filp->f_pos1 32768 len 32768
Oct 21 17:31:20 localhost kernel: filp->f_pos2 40960 len 40960
Oct 21 17:31:20 localhost kernel: filp->f_pos1 40960 len 40960
Oct 21 17:31:20 localhost kernel: filp->f_pos2 49152 len 49152
Oct 21 17:31:20 localhost kernel: filp->f_pos1 49152 len 49152
Oct 21 17:31:20 localhost kernel: filp->f_pos2 57344 len 57344
Oct 21 17:31:20 localhost kernel: filp->f_pos1 57344 len 57344
Oct 21 17:31:20 localhost kernel: filp->f_pos2 65536 len 65536
Oct 21 17:31:20 localhost kernel: filp->f_pos1 65536 len 65536
Oct 21 17:31:20 localhost kernel: filp->f_pos2 73728 len 73728
Oct 21 17:31:20 localhost kernel: filp->f_pos1 73728 len 73728
Oct 21 17:31:20 localhost kernel: filp->f_pos2 81920 len 81920

wwxxxxll 发表于 2013-10-21 14:24

我把
    memset(data, index, data_len);
    filp->f_op->write(filp, data, strlen(data),&filp->f_pos);
改成
    memset(data, index, 10);
    filp->f_op->write(filp, data, sizeof(data),&filp->f_pos);

结果:
root@localhost test]# hexdump /home/file1
0000000 0000 0000 0000 0000 0000 0101 0101 0101
0000010 0101 0101 0202 0202 0202 0202 0202 0303
0000020 0303 0303 0303 0303 0404 0404 0404 0404
0000030 0404 0505 0505 0505 0505 0505 0606 0606
0000040 0606 0606 0606 0707 0707 0707 0707 0707
0000050 0808 0808 0808 0808 0808 0909 0909 0909
0000060 0909 0909                              
0000064
# du -sh /home/file1
4.0K    /home/file1
大小为4.0K应该是因为分页机制,一页为4.0K

不知道,你要什么效果
linux 驱动群:
163617970
页: [1]
查看完整版本: 请教一个内核写文件的问题