Advertisement
xosski

Kernel procfs

Dec 10th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. #include <linux/kernel.h>
  2. #include <linux/module.h>
  3. #include <linux/init.h>
  4. #include <linux/printk.h>
  5. #include <linux/proc_fs.h>
  6. #include <asm/current.h>
  7.  
  8. #define procfs_name "Mythread_info"
  9. #define BUFSIZE  1024
  10. char buf[BUFSIZE];
  11.  
  12. static ssize_t Mywrite(struct file *fileptr, const char __user *ubuf, size_t buffer_len, loff_t *offset){
  13.     /* Do nothing */
  14. return 0;
  15. }
  16.  
  17. static ssize_t Myread(struct file *fileptr, char __user *ubuf, size_t buffer_len, loff_t *offset){
  18.     int len = 0;
  19.     struct task_struct *task;
  20.  
  21.     // 確保內容僅被讀取一次
  22.     if (*offset > 0){
  23.         return 0;
  24.     }
  25.  
  26.     // 初始化緩衝區
  27.     memset(buf, 0, BUFSIZE);
  28.  
  29.     // 取得讀取鎖以安全地遍歷任務列表
  30.     rcu_read_lock();
  31.     
  32.     // 遍歷當前進程的所有執行緒
  33.     for_each_thread(current->group_leader, task){
  34.         if(task->tgid == task->pid) continue;
  35.         // 格式:PID: <PID>, TID: <TID>, Priority: <Priority>, State: <State>
  36.         len += snprintf(buf + len, BUFSIZE - len, "PID: %d, TID: %d, Priority: %d, State: %ld\n",
  37.                        task->tgid,      // 執行緒組 ID(主執行緒的 PID)
  38.                        task->pid,       // 執行緒 ID (TID)
  39.                        task->prio,      // 優先權
  40.                        task->stats);    // 狀態
  41.  
  42.         // 防止緩衝區溢位
  43.         if (len >= BUFSIZE){
  44.             break;
  45.         }
  46.     }
  47.     
  48.     rcu_read_unlock();
  49.  
  50.     // 檢查緩衝區長度是否超過用戶緩衝區
  51.     if (len > buffer_len){
  52.         len = buffer_len;
  53.     }
  54.  
  55.     // 將資料複製到用戶空間
  56.     if (copy_to_user(ubuf, buf, len)){
  57.         return -EFAULT;
  58.     }
  59.  
  60.     // 更新偏移量
  61.     *offset += len;
  62.     return len;
  63. }
  64.  
  65. static struct proc_ops Myops = {
  66.     .proc_read = Myread,
  67.     .proc_write = Mywrite,
  68. };
  69.  
  70. static int My_Kernel_Init(void){
  71.     proc_create(procfs_name, 0644, NULL, &Myops);   
  72.     pr_info("My kernel says Hi");
  73.     return 0;
  74. }
  75.  
  76. static void My_Kernel_Exit(void){
  77.     pr_info("My kernel says GOODBYE");
  78. }
  79.  
  80. module_init(My_Kernel_Init);
  81. module_exit(My_Kernel_Exit);
  82.  
  83. MODULE_LICENSE("GPL");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement