Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 下的 PCB:走進 task_struct 的關鍵欄位

原始檔:/usr/src/linux-headers-4.4.0-22/include/linux/sched.h。task_struct 是內核描述「行程」的核心結構,幾乎每個子系統都會與它打交道。以下保留最具代表性的欄位(部分以註解省略),並逐組說明其含義。

struct task_struct {
    volatile long state;              /* -1 不可執行, 0 可執行, >0 已停止 */
    void *stack;
    atomic_t usage;
    unsigned int flags;               /* 行程標誌 */
    unsigned int ptrace;

    int on_rq;
    int prio, static_prio, normal_prio;
    unsigned int rt_priority;
    const struct sched_class *sched_class;
    struct sched_entity se;           /* 普通排程實體 */
    struct sched_rt_entity rt;        /* 即時排程實體 */
    struct sched_dl_entity dl;        /* deadline 排程實體 */
    unsigned int policy;
    cpumask_t cpus_allowed;

    struct list_head tasks;           /* 全系統行程鏈表 */
    struct mm_struct *mm, *active_mm; /* 記憶體描述 */

    int exit_state;
    int exit_code, exit_signal;
    int pdeath_signal;

    pid_t pid;
    pid_t tgid;                       /* 執行緒群組 ID */

    struct task_struct __rcu *real_parent;  /* 真實父行程 */
    struct task_struct __rcu *parent;       /* 接收 SIGCHLD 者 */
    struct list_head children;        /* 我的子行程鏈表 */
    struct list_head sibling;         /* 在父行程子鏈表中的位置 */
    struct task_struct *group_leader; /* 執行緒群組領袖 */

    struct list_head ptraced;
    struct list_head ptrace_entry;
    struct pid_link pids[PIDTYPE_MAX];
    struct list_head thread_group;

    cputime_t utime, stime;           /* 使用者/核心時間 */
    u64 start_time;
    unsigned long min_flt, maj_flt;   /* 缺頁與主缺頁次數 */

    const struct cred __rcu *real_cred;
    const struct cred __rcu *cred;    /* 權限憑證 */

    char comm[TASK_COMM_LEN];         /* 行程名稱 */

    struct fs_struct *fs;             /* 檔案系統資訊 */
    struct files_struct *files;       /* 開啟的檔案 */
    struct nsproxy *nsproxy;          /* 命名空間 */
    struct signal_struct *signal;
    struct sighand_struct *sighand;
    sigset_t blocked, real_blocked;

    spinlock_t alloc_lock;
    raw_spinlock_t pi_lock;

    struct io_context *io_context;
    struct task_io_accounting ioac;

    /* ... 其餘 CONFIG_* 條件編譯欄位省略 ... */

    struct thread_struct thread;      /* CPU 相關狀態,必須放在最後 */
};

幾個最值得先記住的欄位

state:行程狀態,-1 不可執行、0 可執行(running)、正數代表停止,是排程器判斷的第一依據。

sched_class / se / rt / dl:CFS、RT、deadline 三種排程策略各自掛在這裡,sched_class 指向具體的排程類別介面。

tasks:把所有行程串成一條雙向鏈表,核心中大量「遍歷所有行程」的操作都靠它。

mm / active_mm:記憶體描述;核心執行緒沒有 mm,會借用 active_mm。

pid / tgid:pid 是該執行緒的 ID,tgid 是執行緒群組 ID,單執行緒行程兩者相同。

real_parent / parent / children / sibling:家族關係網。real_parent 是真實生父,parent 則是 SIGCHLD 的接收者,除錯(ptrace)時兩者會不同。

cred:權限憑證,ruid/euid 等實際與有效權限都在其中,是權限檢查的入口。

files / fs / nsproxy:開啟的檔案、根目錄與工作目錄、以及各類命名空間,容器技術的隔離就靠 nsproxy。

thread:架構相關狀態,在 x86 上大小不固定,因此必須放在結構的最後,這個約定不能破壞。

另外,大量欄位被 #ifdef CONFIG_* 包住,代表 task_struct 的大小與佈局會隨核心組態而變——這也是為什麼外部模組不能假設欄位偏移固定。

Copyright © Linux教程網 All Rights Reserved