read_proc的用法執行個體

來源:互聯網
上載者:User

說明

本測試程式主要參考了《linux裝置驅動程式》第三版的第四章“調試技術”的‘/proc檔案’一節。

並對一些關鍵函數進行了執行個體化。

以下是mod1.c

#include<linux/init.h>

#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/proc_fs.h>   /* read_proc需要的標頭檔。 */

MODULE_LICENSE("GPL");
/*
    原型函數:int (*read_proc)(char *page, char **start, off_t offset, int count, int *eof, void *data)
    這個函數與read的系統調用函數功能類似。就在/proc中為驅動程式設計了一個特有了檔案(假設名scull)後,則使用者使用cat /proc/scull時,會調用到此函數。
    在/proc中建立檔案,並且完成此檔案與一個read_proc的關聯關係的函數是create_proc_read_entry.
    刪除這種關係,並且刪除這個檔案的函數是remove_proc_entry.
    實體函數:scull_read_procmem(char *buf, char **start, off_t offset, int count, int *eof, void *data)

parameter:
    buf:是從驅動層嚮應用層返回的資料區;當有使用者讀此/proc/xxx的檔案時,由系統分配一頁的緩衝區,驅動使用read_proc此寫入資料。
    start: 表示寫在此頁的哪裡,此用法複雜,如果是返回小量資料(不超過一頁)賦值為NULL。
    offset:與read用法一致,表示檔案指標的位移。
    count:與read用法一致,表示要讀多少個位元組。
    eof:  輸出參數。
    data:由驅動內部使用。
return:
    傳回值是可讀到的位元組數。
*/
int scull_read_procmem(char *buf, char **start, off_t offset, int count, int *eof, void *data)

{
    int len = 0;
    
    len += sprintf(buf + len, "I am peter\r\n and thank you\r\n");
    *eof = 1;
    return len;
}

static int func1(void)
{
        printk("In Func: %s...\n",__func__);
        
        return 0;
}

EXPORT_SYMBOL(func1);

static int __init hello_init(void)
{
/* 當你定義了read_proc函數,你就需要將它串連到/proc目錄中的某個條目。這個工作可以藉助一個叫做create_proc_read_entry的函數完成
struct proc_dir_entry *create_proc_read_entry(const char *name, mode_t mode, struct proc_dir_entry *base, read_proc_t *read_proc, void *data)
參數:
name是要建立的/proc檔案名稱,
mode是檔案的保護掩碼(0為系統預設值),
base指明建立檔案的目錄(如果設定為NULL,檔案就建立在/proc根目錄下),
read_proc是read_proc函數的入口地址,
data被核心忽略(但會被傳遞給read_proc函數)。
*/
    create_proc_read_entry("scullmem",
        0 /* default mode */,
        NULL /* parent dir */,
        scull_read_procmem,
        NULL /* client data */);
        
        printk("Module 1,Init!\n");
        return 0;
}

static void __exit hello_exit(void)
{
    remove_proc_entry("scullmem", NULL /* parent dir */);
    printk("Module 1,Exit!\n");
}

module_init(hello_init);
module_exit(hello_exit);

聯繫我們

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