Linux核心態下的檔案操作

來源:互聯網
上載者:User

轉自http://z515256164.blog.163.com/blog/static/32443029201211362335184/

在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 
#include
#include
#include
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);
    pos = 0;
    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");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.