通過proc檔案系統讓Linux核心空間和使用者空間之間進行通訊

來源:互聯網
上載者:User

1. 現象和問題描述

1.需要在linux使用者態下通過指令碼直接跟核心互動,比如擷取/設定核心中某些變數的值。

2.需要在linux核心下啟動運行時動態配置。

2. 關鍵過程和根本原因分析

/proc 檔案系統是一個虛擬檔案系統,通過它可以使用一種新的方法在 Linux核心空間和使用者空間之間進行通訊。在 /proc 檔案系統中,我們可以將對虛擬檔案的讀寫作為與核心中實體進行通訊的一種手段,但是與普通檔案不同的是,這些虛擬檔案的內容都是動態建立的。

3. 附加案例檔案

說明:

示範在核心中開闢一個緩衝區,然後在使用者態下對它進行讀寫

比如,

讀 - cat /proc/ooxx

寫 - echo "mydata" > /proc/ooxx。

代碼清單:

 #define ITEM_NAME "ooxx"<br />static struct proc_dir_entry *proc_entry;<br />static char g_buf[PAGE_SIZE];</p><p>ssize_t ooxx_write(struct file *pf, const char __user *buf, unsigned long len, void *data)<br />{<br /> memset(g_buf, 0, PAGE_SIZE);<br /> if (copy_from_user(g_buf, buf, len)) {<br /> printk("copy_from_user fail./n");<br /> return -EFAULT;<br /> }<br /> return strlen(g_buf);<br />}</p><p>int ooxx_read(char *page, char **start, off_t off, int count, int *eof, void *data)<br />{<br /> sprintf(page, "%s/n", g_buf);<br /> return strlen(g_buf);<br />}</p><p>int __init demo_proc_init(void)<br />{</p><p> printk("%s: enter./n", __FUNCTION__);<br /> sprintf(g_buf, "ooxx/n");</p><p> /* 第三個參數NULL表示在proc根目錄下建立 */<br /> proc_entry = create_proc_entry(ITEM_NAME, S_IRUGO |S_IWUGO, NULL);</p><p> if (NULL != proc_entry) {<br /> printk("ok/n");<br /> proc_entry->read_proc = ooxx_read;<br /> proc_entry->write_proc = ooxx_write;<br /> proc_entry->owner = THIS_MODULE;<br /> }<br /> printk("%s: leave./n", __FUNCTION__);<br /> return 0;<br />}</p><p>void __exit demo_proc_exit(void)<br />{<br /> printk("%s: enter./n", __FUNCTION__);<br /> if (NULL != proc_entry) {<br /> printk("release/n");<br /> remove_proc_entry(ITEM_NAME, &proc_root);<br /> }<br /> printk("%s: leave./n", __FUNCTION__);<br /> return;<br />}</p><p>MODULE_LICENSE("GPL");<br />module_init(demo_proc_init);<br />module_exit(demo_proc_exit);<br /> 

 

具體參考:使用/proc檔案系統來訪問Linux核心的內容—這個虛擬檔案系統在核心空間和使用者空間之間開啟了一個通訊視窗

相關文章

聯繫我們

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