Linux kernel (without create_proc_entry func) Proc檔案系統的執行個體__Linux

來源:互聯網
上載者:User
proc檔案系統

/proc 目錄就是Linux的proc檔案系統了, 這裡面存放核心的配置資訊, 網路設定系統, 以及進程的狀態都是以pid明明的目錄。總之, 關於核心的基本配置你就可以找到。 核心更新

在核心的迭代過程中,總有一些介面被廢棄, create_proc_entry就是其中之一。
依稀記得,去年的時候一直想寫個proc檔案系統測試下, 直到上個月才有時間來做這個事情。當初讓我試了就不測試的原因就是那個create_proc_entry函數的棄用, 網上能搜尋的例子基本都是用這個函數。 範例代碼

#include <linux/module.h>#include <linux/proc_fs.h>#include <linux/seq_file.h>#include <asm/uaccess.h>#include <linux/slab.h>static char *buffer = NULL;static int hello_proc_show(struct seq_file *m, void *v) {  seq_printf(m, "Hello proc!\n");  seq_printf(m, "buffer=%s\n", buffer);  int i = 0;  if (buffer != NULL)  {      if (buffer[0] == 's')    {      for (i = 0; i < 10; i++)        seq_printf(m, "i = %d\n", i);    }  }  return 0;}static ssize_t hello_proc_write(struct file *file, const char *buffer, size_t len,  loff_t *off){  int user_len = 0;  user_len = len;  buffer = (char *)kmalloc(user_len+1, GFP_KERNEL);  memset(buffer, 0, user_len + 1);  if (copy_from_user(buffer, buffer, user_len))  {    printk( "hello_proc error\n");    return -EFAULT;  }  printk( "userlen=%d\n", user_len);  return user_len;}static int hello_proc_open(struct inode *inode, struct  file *file) {  return single_open(file, hello_proc_show, NULL);}static const struct file_operations hello_proc_fops = {  .owner = THIS_MODULE,  .open = hello_proc_open,  .read = seq_read,  .write = hello_proc_write,  .llseek = seq_lseek,  .release = single_release,};static int __init hello_proc_init(void) {  proc_create("hello_proc", 0666, NULL, &hello_proc_fops);  return 0;}static void __exit hello_proc_exit(void) {  remove_proc_entry("hello_proc", NULL);}MODULE_LICENSE("GPL");module_init(hello_proc_init);module_exit(hello_proc_exit);
範例代碼注釋

功能: 其在/proc目錄下建立了hello_proc檔案,

echo s >/proc/hello_proccat /proc/hello_proc這樣就會有輸出資訊了。

seq_file 是核心提供的序列介面, 詳情就不介紹了,這種方式當資料大的時候記憶體配置不需要你去關心, 非常實用。

源碼地址:qianguozheng

聯繫我們

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