有时候调试过程中需要在内核里面对文件进行操作,但是应用层的系统调用都不可用,像open,read,write或者标准库的fopen,fread,fwrite函数,在linux内核其实可以用如下方式进行文件读写操作。

下面是一个例子,我以前在调试LCD,由于fb数据不正常。需要抓取每一帧图像进行分析用到的例子。

static int save_the_buffer(void *fb_data)
{
    static char path[] = "/data/mybuffer1000";
    static int __num__ = 0;

    struct file *filp;
    int error_num  = 0 ;
    size_t  ret = 0,fb_size = 240*320*3;
    mm_segment_t old_fs;
    void *data  = fb_data;
    sprintf(path,"/data/mybuffer%d", __num__++);
    old_fs = get_fs();
    set_fs(KERNEL_DS);//设置为kernel

    DISPERR("save_the_buffer is ++++++++\n");
    filp = filp_open(path, O_CREAT|O_RDWR,0600);//filp_open类似open返回一个filp指针
    error_num  = PTR_ERR(filp);
    if (error_num < 0) {
        DISPERR("open error ++++++++++ %s\n", path);
        DISPERR("error num is :[%d]\n",error_num);
        filp = NULL;
        return error_num;
    }

    //write
    ret= vfs_write(filp, (char __user *)data, fb_size, &filp->f_pos);//将需要保存的buf保存到文件
    DISPERR("%s - wirte done ++++++++++++++++++\n", __func__);

    set_fs(old_fs);

    filp_close(filp, current->files);//记得关闭文件

    return 0;

}

Logo

更多推荐