天天看點

Linux驅動 讀寫檔案【轉】

在VFS的支援下,使用者态程序讀寫任何類型的檔案系統都可以使用read和write着兩個系統調用,但是在linux核心中沒有這樣的系統調用我們如何操作檔案呢?我們知道read和write在進入核心态之後,實際執行的是sys_read和sys_write,但是檢視核心源代碼,發現這些操作檔案的函數都沒有導出(使用EXPORT_SYMBOL導出),也就是說在核心子產品中是不能使用的,那如何是好?

通過檢視sys_open的源碼我們發現,其主要使用了do_filp_open()函數,該函數在fs/namei.c中,而在改檔案中,filp_open函數也是調用了do_filp_open函數,并且接口和sys_open函數極為相似,調用參數也和sys_open一樣,并且使用EXPORT_SYMBOL導出了,是以我們猜想該函數可以打開檔案,功能和open一樣。使用同樣的查找方法,我們找出了一組在核心中操作檔案的函數,如下:

功能

函數原型

打開檔案

struct file *filp_open(const char *filename, int flags, int mode)

讀取檔案

ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)

寫檔案

ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)

關閉檔案

int filp_close(struct file *filp, fl_owner_t id)

我們注意到在vfs_read和vfs_write函數中,其參數buf指向的使用者空間的記憶體位址,如果我們直接使用核心空間的指針,則會傳回-EFALUT。是以我們需要使用

set_fs()和get_fs()宏來改變核心對記憶體位址檢查的處理方式,是以在核心空間對檔案的讀寫流程為:

mm_segment_t fs = get_fs();

set_fs(KERNEL_FS);

//vfs_write();

vfs_read();

set_fs(fs);

下面為一個在核心中對檔案操作的例子:

#include <linux/module.h>

#include <linux/init.h>

#include <linux/fs.h>

#include <linux/uaccess.h>

static char buf[] = "你好";

static char buf1[10];

int __init hello_init(void)

{

    struct file *fp;

    mm_segment_t fs;

    loff_t pos;

    printk("hello enter\n");

    fp = filp_open("/home/niutao/kernel_file", O_RDWR | O_CREAT, 0644);

    if (IS_ERR(fp)) {

        printk("create file error\n");

        return -1;

    }

    fs = get_fs();

    set_fs(KERNEL_DS);

    pos = 0;

    vfs_write(fp, buf, sizeof(buf), &pos);

    vfs_read(fp, buf1, sizeof(buf), &pos);

    printk("read: %s\n", buf1);

    filp_close(fp, NULL);

    set_fs(fs);

    return 0;

}

void __exit hello_exit(void)

    printk("hello exit\n");

module_init(hello_init);

module_exit(hello_exit);

MODULE_LICENSE("GPL");

本文轉自張昺華-sky部落格園部落格,原文連結:http://www.cnblogs.com/sky-heaven/p/5542912.html,如需轉載請自行聯系原作者

繼續閱讀