Linux 核心態檔案操作

來源:互聯網
上載者:User

在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()宏來改變核心對記憶體位址檢查的處理方式,所以在核心空間對檔案的讀寫流程為:

  1. mm_segment_t fs = get_fs();
  2. set_fs(KERNEL_FS);
  3. //vfs_write();
  4. vfs_read();
  5. set_fs(fs);

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

#include #include#include#includestatic 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");

以上內容轉自:http://www.ej38.com/showinfo/linux-192439.html

另外有個問題,想要在核心態擷取檔案屬性(目錄檔案、普通檔案、uid、gid), 該用什麼方法呢? 

使用者態的方法是使用 stat 系統調用,但是核心態這個系統調用是沒有匯出的,所以不能使用。

不知道 sys_stat 和 vfs_stat 可以實現不,正在努力嘗試中 ........

收藏

http://www.iteedu.com//os/linux/linuxprgm/linuxcfunctions/index.php

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.