2011-12-15 19 views
27

Ai đó có thể cho tôi ví dụ proc_create()?Ví dụ về proc_create() cho mô-đun hạt nhân

Trước đó, họ đã sử dụng create_proc_entry() trong hạt nhân nhưng giờ đây họ đang sử dụng proc_create().

+1

tại sao không chỉ tải về mã nguồn kernel hiện tại và grep cho proc_create? – Roland

Trả lời

30

Ví dụ này sẽ tạo mục nhập proc cho phép truy cập đọc. Tôi nghĩ bạn có thể bật các loại quyền truy cập khác bằng cách thay đổi đối số mode được chuyển đến hàm. Tôi đã không vượt qua một thư mục cha bởi vì không cần phải. Cấu trúc file_operations là nơi bạn thiết lập các cuộc gọi lại và đọc của mình.

struct proc_dir_entry *proc_file_entry; 

static const struct file_operations proc_file_fops = { 
.owner = THIS_MODULE, 
.open = open_callback, 
.read = read_callback, 
}; 

int __init init_module(void){ 
    proc_file_entry = proc_create("proc_file_name", 0, NULL, &proc_file_fops); 
    if(proc_file_entry == NULL) 
    return -ENOMEM; 
    return 0; 
} 

Bạn có thể kiểm tra ví dụ này để biết thêm chi tiết: https://www.linux.com/learn/linux-training/37985-the-kernel-newbie-corner-kernel-debugging-using-proc-qsequenceq-files-part-1

+0

Nhìn vào nguồn hạt nhân tôi nên đưa ra một nhận xét. 'proc_file_fops' không được đặt trong bộ nhớ ngăn xếp (biến cục bộ chức năng). Nó phải là một biến toàn cầu hoặc được đặt trong bộ nhớ được cấp phát với một số chức năng bộ nhớ heap. –

21

Đây là một 'hello_proc' mã, mà làm cho việc sử dụng phiên bản mới hơn 'proc_create()' giao diện.

#include <linux/module.h> 
#include <linux/proc_fs.h> 
#include <linux/seq_file.h> 

static int hello_proc_show(struct seq_file *m, void *v) { 
    seq_printf(m, "Hello proc!\n"); 
    return 0; 
} 

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, 
    .llseek = seq_lseek, 
    .release = single_release, 
}; 

static int __init hello_proc_init(void) { 
    proc_create("hello_proc", 0, 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); 

Mã này đã được lấy từ http://pointer-overloading.blogspot.in/2013/09/linux-creating-entry-in-proc-file.html

+1

Cảm ơn bạn đã liên kết, thực sự hữu ích. Tôi khuyên bạn nên đọc cho những người muốn hiểu cách hoạt động của nó. –

+1

Ví dụ này với [QEMU + Bản mẫu thử nghiệm Buildroot] (https://github.com/cirosantilli/linux-kernel-module-cheat/blob/4727fadcc8f6e0685f80dc88a2913995a8df01f3/kernel_module/procfs.c). –