進程管理—進程描述符(task_struct)

前言


當把一個程序加載到內存當中,此時,這個時候就有了進程,關於進程,有一個相關的叫做進程控制塊(PCB),這個是系統爲了方便進行管理進程所設置的一個數據結構,通過PCB,就可以記錄進程的特徵以及一些信息。
內核當中使用進程描述符task_struct。
這個task_struct就是一個定義的一個結構體,通過這個結構體,可以對進程的所有的相關的信息進行維護,對進程進行管理。

接下來我們需要對task_struct結構體當中的成員進行一些分析。

linux內核版本
Linux version 2.6.32-431.el6.i686

1 task_struct


1.1 進程狀態


volatile long state;
int exit_state;`

表示進程的狀態,
在進程執行的時候,它會有一個狀態,這個狀態對於進程來說是很重要的一個屬性。進程主要有以下幾個狀態。

state可能的取值
這裏寫圖片描述

這裏寫圖片描述
這些狀態就不再一一說明了,後續進程篇會有專門的說明。

1.2 進程標識符(PID)


pid_t pid;
pid_t tgid;

每個進程都有進程標識符、用戶標識符、組標識符,進程標識符對於每一個進程來說都是唯一的。內核通過進程標識符來對不同的進程進行識別,一般來說,行創建的進程都是在前一個進程的基礎上PID加上1作爲本進程的PID。爲了linux平臺兼容性,PID一般最大爲32767。

1.3 進程內核棧


void *stack

stack用來維護分配給進程的內核棧,內核棧的意義在於,進程task_struct所佔的內存是由內核動態分配的,確切的說就是內核根本不給task_struct分配內存,只給內核棧分配8KB內存,並且一部分會提供給task_struct使用。
task_struct結構體大約佔用的大小爲1K左右,根據內核版本的不同,大小也會有差異。
所以,也就可以知道內核棧最大也就是7KB,否則,內核棧會覆蓋task_struct結構。

1.4 標記


unsigned int flags

用來反映一個進程的狀態信息,但不是運行狀態,用於內核識別進程當前的狀態,flags的取值如下:

可使用的標記 功能
PF_FORKNOEXEC 進程剛創建,但還沒執行。
PF_SUPERPRIV 超級用戶特權。
PF_DUMPCORE 關於核心。
PF_SIGNALED 進程被信號(signal)殺出。
PF_EXITING 進程開始關閉。

1.5 表示進程親屬關係的成員


struct task_struct *real_parent;
struct task_struct *parent;
struct list_head children;
struct list_head sibling;
struct task_struct *group_leader;

linux系統當中,考慮到進程的派生,所以進程之間會存在父進程和子進程這樣的關係,當然,對於同一個父進程派生出來的進程,他們的關係當然是兄弟進程了。

成員 功能
real_parent 指向父進程的指針,如果父進程不存在了,則指向PID爲1的進程
parent 指向父進程的,值與real——parent相同,需要向它的父進程發送信號
children 表示鏈表的頭部,鏈表中的所有元素都是它的子進程
sibling 用於當前進程插入兄弟鏈表當中
group_leader 指向進程組的領頭進程

1.6 ptrace系統調用


unsigned int ptrace;
struct list_head ptraced;
struct list_head ptrace_entry;

首先我們要清楚ptrace是什麼東西,ptrace是一種提供父進程控制子進程運行,並且可以檢查和改變它的核心image。當trace設置爲0時不需要被跟蹤。

1.7 性能診斷工具——Performance Event


#ifdef CONFIG_PERF_EVENTS
#ifndef __GENKSYMS__
    void * __reserved_perf__;
#else
    struct perf_event_context *perf_event_ctxp;
#endif
    struct mutex perf_event_mutex;
    struct list_head perf_event_list;
#endif

Performance Event是性能診斷工具,這些成員用來幫助它進行分析進程性能問題。

1.8 進程調度


    int prio, static_prio, normal_prio;
    unsigned int rt_priority;
成員 功能
static_prio 保存靜態優先級,可以通過nice系統進行修改
rt_priority 保存實時優先級
normal_prio 保存靜態優先級和調度策略
prio 保存動態優先級

調度進程利用這部分信息決定系統當中的那個進程最應該運行,並且結合進程的狀態信息保證系統運作高效。

提到進程調度,當然還需要說明一下進程調度策略,我們來看下關於調度策略的成員:

    unsigned int policy;
    const struct sched_class *sched_class;
    struct sched_entity se;
    struct sched_rt_entity rt;
成員 功能
policy 調度策略
sched_class 調度類
se 普通進程的一個調用的實體,每一個進程都有其中之一的實體
rt 實時進程的調用實體,每個進程都有其中之一的實體
cpus_allowed 用於控制進程可以在處理器的哪裏運行

policy表示進程的調度策略,主要有以下五種:

種類 功能
SCHED_NORMAL 用於普通進程
SCHED_BATCH 普通進程策略的分化版本,採用分時策略
SCHED_IDLE 優先級最低,系統空閒時才跑這類進程
SCHED_FIFO 先入先出的調度算法
SCHED_RR 實時調度算法,採用時間片,相同優先級的任務當用完時間片就會放到隊列的尾部,保證公平性,同時,高優先級的任務搶佔低優先級的任務。
SCHED_DEADLINE 新支持的實時調度策略,正對突發性計算

說完了調度策略,我們再來看一下調度類。

調度類 功能
idle_sched_class 每一個cpu的第一個pid=0的線程,是一個靜態的線程
stop_sched_class 優先級最高的線程,會中斷所有其他的線程,而且不會被其他任務打斷
rt_sched_slass 作用在實時線程
fair_sched_class 作用的一般線程

它們的優先級順序爲Stop>rt>fair>idle

1.9進程的地址空間


    struct mm_struct *mm, *active_mm;
成員 功能
mm 進程所擁有的用戶空間的內存描述符
active_mm 指向進程運行時使用的內存描述符,對於普通的進程來說,mm和active_mm是一樣的,但是內核線程是沒有進程地址空間的,所以內核線程的mm是空的,所以需要初始化內核線程的active_mm

對於內核線程切記是沒有地址空間的。

後續會有專門的博客來敘述

1.10 判斷標誌


    //用於進程判斷標誌
    int exit_state;
    int exit_code, exit_signal;
    int pdeath_signal;  /*  The signal sent when the parent dies  */
    /* ??? */
    unsigned int personality;
    unsigned did_exec:1;
    unsigned in_execve:1;   /* Tell the LSMs that the process is doing an
                 * execve */
    unsigned in_iowait:1;

    /* Revert to default priority/policy when forking */
    unsigned sched_reset_on_fork:1;
成員 功能
exit_state 進程終止的狀態
exit_code 設置進程的終止代號
exit_signal 設置爲-1的時候表示是某個線程組當中的一員,只有當線程組的最後一個成員終止時,纔會產生型號給父進程
pdeath_signal 用來判斷父進程終止時的信號

1.11 時間與定時器


關於時間,一個進程從創建到終止叫做該進程的生存期,進程在其生存期內使用CPU時間,內核都需要進行記錄,進程耗費的時間分爲兩部分,一部分是用戶模式下耗費的時間,一部分是在系統模式下耗費的時間。

    //描述CPU時間的內容
    cputime_t utime, stime, utimescaled, stimescaled;
    cputime_t gtime;
    cputime_t prev_utime, prev_stime;
    unsigned long nvcsw, nivcsw; /* context switch counts */
    struct timespec start_time;         /* monotonic time */
    struct timespec real_start_time;    /* boot based time */
    struct task_cputime cputime_expires;
    struct list_head cpu_timers[3];
成員 屬性
utime/stime 用於記錄進程在用戶狀態/內核態下所經過的定時器
prev_utime/prev_stime 記錄當前的運行時間
utimescaled/stimescaled 分別記錄進程在用戶態和內核態的運行的時間
gtime 記錄虛擬機的運行時間
nvcsw/nicsw 是自願/非自願上下文切換計數
start_time/real_start_time 進程創建時間,real還包括了進程睡眠時間
cputime_expires 用來統計進程或進程組被跟蹤的處理器時間,三個成員對應的是下面的cpu_times[3]的三個鏈表

然後接下來我們來看一下進程的定時器,一共是三種定時器。

定時器類型 解釋 更新時刻
ITIMER_REAL 實時定時器 實時更新,不在乎進程是否運行
ITIMER_VIRTUAL 虛擬定時器 只在進程運行用戶態時更新
ITIMER_PROF 概況定時器 進程運行於用戶態和系統態進行更新

進程總過有三種定時器,這三種定時器的特徵有到期時間,定時間隔,和要觸發的時間,

1.12 信號處理


    struct signal_struct *signal;
    struct sighand_struct *sighand;

    sigset_t blocked, real_blocked;
    sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
    struct sigpending pending;

    unsigned long sas_ss_sp;
    size_t sas_ss_size;

關於信號處理:

成員 功能
signal 指向進程信號描述符
sighand 指向進程信號處理程序描述符
blocked 表示被阻塞信號的掩碼
pending 存放私有掛起信號的數據結構
sas_ss_sp 信號處理程序備用堆棧的地址

1.13 文件系統信息


    //文件系統信息結構體
/* filesystem information */
    struct fs_struct *fs;

    //打開文件相關信息結構體
/* open file information */
    struct files_struct *files;

進程可以用來打開和關閉文件,文件屬於系統資源,task_struct有兩個來描述文件資源,他們會描述兩個VFS索引節點,兩個節點分別是root和pwd,分別指向根目錄和當前的工作目錄。

成員 功能
struct fs_struct *fs 進程可執行鏡像所在的文件系統
struct files_struct *files 進程當前打開的文件

1.14 其他


struct task_struct {
    //進程狀態(-1就緒態,0運行態,>0停止態)
    volatile long state;    /* -1 unrunnable, 0 runnable, >0 stopped */

    //進程內核棧
    void *stack;

    //有幾個進程只在使用此結構
    atomic_t usage;

    //標記
    unsigned int flags; /* per process flags, defined below */

    //ptrace系統調用,關於實現斷點調試,跟蹤進程運行。
    unsigned int ptrace;

    //鎖的深度
    int lock_depth;     /* BKL lock depth */

    //SMP實現無加鎖的進程切換
#ifdef CONFIG_SMP
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
    int oncpu;
#endif
#endif

    //關於進程調度
    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;

    //preempt_notifier結構體鏈表
#ifdef CONFIG_PREEMPT_NOTIFIERS
    /* list of struct preempt_notifier: */
    struct hlist_head preempt_notifiers;
#endif

    /*
     * fpu_counter contains the number of consecutive context switches
     * that the FPU is used. If this is over a threshold, the lazy fpu
     * saving becomes unlazy to save the trap. This is an unsigned char
     * so that after 256 times the counter wraps and the behavior turns
     * lazy again; this to deal with bursty apps that only use FPU for
     * a short time
     */

     //FPU使用計數
    unsigned char fpu_counter;

    //塊設備I/O層的跟蹤工具
#ifdef CONFIG_BLK_DEV_IO_TRACE
    unsigned int btrace_seq;
#endif
    //進程調度策略相關的字段
    unsigned int policy;

    cpumask_t cpus_allowed;

    //RCU同步原語
#ifdef CONFIG_TREE_PREEMPT_RCU
    int rcu_read_lock_nesting;
    char rcu_read_unlock_special;
    struct rcu_node *rcu_blocked_node;
    struct list_head rcu_node_entry;
#endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */

//用於調度器統計進程運行信息
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
    struct sched_info sched_info;
#endif

//用於構架進程鏈表
    struct list_head tasks;
    struct plist_node pushable_tasks;

    //關於進程的地址空間,指向進程的地址空間。(鏈表和紅黑樹)
    struct mm_struct *mm, *active_mm;

/* task state */
    //進程狀態參數
    int exit_state;

    //退出信號處理
    int exit_code, exit_signal;

    //接收父進程終止的時候會發送信號
    int pdeath_signal;  /*  The signal sent when the parent dies  */
    /* ??? */
    unsigned int personality;
    unsigned did_exec:1;
    unsigned in_execve:1;   /* Tell the LSMs that the process is doing an
                 * execve */
    unsigned in_iowait:1;


    /* Revert to default priority/policy when forking */
    unsigned sched_reset_on_fork:1;

    //進程pid,父進程ppid。
    pid_t pid;
    pid_t tgid;

    //防止內核堆棧溢出
#ifdef CONFIG_CC_STACKPROTECTOR
    /* Canary value for the -fstack-protector gcc feature */
    unsigned long stack_canary;
#endif

    /*
     * pointers to (original) parent process, youngest child, younger sibling,
     * older sibling, respectively.  (p->father can be replaced with
     * p->real_parent->pid)
     */

     //這部分是用來進行維護進程之間的親屬關係的。
     //初始化父進程
    struct task_struct *real_parent; /* real parent process */
    //接納終止的進程
    struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */
    /*
     * children/sibling forms the list of my natural children
     */
     //維護子進程鏈表
    struct list_head children;  /* list of my children */
    //兄弟進程鏈表
    struct list_head sibling;   /* linkage in my parent's children list */
    //線程組組長
    struct task_struct *group_leader;   /* threadgroup leader */

    /*
     * ptraced is the list of tasks this task is using ptrace on.
     * This includes both natural children and PTRACE_ATTACH targets.
     * p->ptrace_entry is p's link on the p->parent->ptraced list.
     */

     //ptrace,系統調用,關於斷點調試。
    struct list_head ptraced;
    struct list_head ptrace_entry;

    //PID與PID散列表的聯繫
    /* PID/PID hash table linkage. */
    struct pid_link pids[PIDTYPE_MAX];

    //維護一個鏈表,裏面有該進程所有的線程
    struct list_head thread_group;

    //do_fork()函數
    struct completion *vfork_done;      /* for vfork() */
    int __user *set_child_tid;      /* CLONE_CHILD_SETTID */
    int __user *clear_child_tid;        /* CLONE_CHILD_CLEARTID */

    //描述CPU時間的內容
    //utime是用戶態下的執行時間
    //stime是內核態下的執行時間
    cputime_t utime, stime, utimescaled, stimescaled;
    cputime_t gtime;
    cputime_t prev_utime, prev_stime;

    //上下文切換計數
    unsigned long nvcsw, nivcsw; /* context switch counts */
    struct timespec start_time;         /* monotonic time */
    struct timespec real_start_time;    /* boot based time */
/* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */

    //缺頁統計
    unsigned long min_flt, maj_flt;

    struct task_cputime cputime_expires;
    struct list_head cpu_timers[3];

/* process credentials */

//進程身份憑據
    const struct cred *real_cred;   /* objective and real subjective task
                     * credentials (COW) */
    const struct cred *cred;    /* effective (overridable) subjective task
                     * credentials (COW) */
    struct mutex cred_guard_mutex;  /* guard against foreign influences on
                     * credential calculations
                     * (notably. ptrace) */
    struct cred *replacement_session_keyring; /* for KEYCTL_SESSION_TO_PARENT */

    //去除路徑以後的可執行文件名稱,進程名
    char comm[TASK_COMM_LEN]; /* executable name excluding path
                     - access with [gs]et_task_comm (which lock
                       it with task_lock())
                     - initialized normally by setup_new_exec */
/* file system info */

    //文件系統信息
    int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc stuff */
//進程通信
    struct sysv_sem sysvsem;
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
/* hung task detection */
    unsigned long last_switch_count;
#endif

//該進程在特點CPU下的狀態
/* CPU-specific state of this task */
    struct thread_struct thread;

    //文件系統信息結構體
/* filesystem information */
    struct fs_struct *fs;

    //打開文件相關信息結構體
/* open file information */
    struct files_struct *files;
/* namespaces */
//命名空間:
    struct nsproxy *nsproxy;
/* signal handlers */

    //關於進行信號處理
    struct signal_struct *signal;
    struct sighand_struct *sighand;

    sigset_t blocked, real_blocked;
    sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
    struct sigpending pending;

    unsigned long sas_ss_sp;
    size_t sas_ss_size;
    int (*notifier)(void *priv);
    void *notifier_data;
    sigset_t *notifier_mask;

    //進程審計
    struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
    uid_t loginuid;
    unsigned int sessionid;
#endif
    seccomp_t seccomp;


#ifdef CONFIG_UTRACE
    struct utrace *utrace;
    unsigned long utrace_flags;
#endif

//線程跟蹤組
/* Thread group tracking */
    u32 parent_exec_id;
    u32 self_exec_id;
/* Protection of (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed,
 * mempolicy */
    spinlock_t alloc_lock;

    //中斷
#ifdef CONFIG_GENERIC_HARDIRQS
    /* IRQ handler threads */
    struct irqaction *irqaction;
#endif

//task_rq_lock函數所使用的鎖
    /* Protection of the PI data structures: */
    spinlock_t pi_lock;

    //基於PI協議的等待互斥鎖
#ifdef CONFIG_RT_MUTEXES
    /* PI waiters blocked on a rt_mutex held by this task */
    struct plist_head pi_waiters;
    /* Deadlock detection and priority inheritance handling */
    struct rt_mutex_waiter *pi_blocked_on;
#endif

//死鎖檢測
#ifdef CONFIG_DEBUG_MUTEXES
    /* mutex deadlock detection */
    struct mutex_waiter *blocked_on;
#endif

//中斷
#ifdef CONFIG_TRACE_IRQFLAGS
    unsigned int irq_events;
    int hardirqs_enabled;
    unsigned long hardirq_enable_ip;
    unsigned int hardirq_enable_event;
    unsigned long hardirq_disable_ip;
    unsigned int hardirq_disable_event;
    int softirqs_enabled;
    unsigned long softirq_disable_ip;
    unsigned int softirq_disable_event;
    unsigned long softirq_enable_ip;
    unsigned int softirq_enable_event;
    int hardirq_context;
    int softirq_context;
#endif

//lockdep
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
    u64 curr_chain_key;
    int lockdep_depth;
    unsigned int lockdep_recursion;
    struct held_lock held_locks[MAX_LOCK_DEPTH];
    gfp_t lockdep_reclaim_gfp;
#endif

//日誌文件
/* journalling filesystem info */

    void *journal_info;

/* stacked block device info */
    //塊設備鏈表
    struct bio *bio_list, **bio_tail;

/* VM state */
    //虛擬內存狀態,內存回收
    struct reclaim_state *reclaim_state;

    //存放塊設備I/O流量信息
    struct backing_dev_info *backing_dev_info;

    //I/O調度器所用信息
    struct io_context *io_context;

    unsigned long ptrace_message;
    siginfo_t *last_siginfo; /* For ptrace use.  */

    //記錄進程I/O計數
    struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
    u64 acct_rss_mem1;  /* accumulated rss usage */
    u64 acct_vm_mem1;   /* accumulated virtual memory usage */
    cputime_t acct_timexpd; /* stime + utime since last update */
#endif

    //CPUSET功能
#ifdef CONFIG_CPUSETS
    nodemask_t mems_allowed;    /* Protected by alloc_lock */
#ifndef __GENKSYMS__
    /*
     * This does not change the size of the struct_task(2+2+4=4+4)
     * so the offsets of the remaining fields are unchanged and 
     * therefore the kABI is preserved.  Only the kernel uses
     * cpuset_mem_spread_rotor and cpuset_slab_spread_rotor so
     * it is safe to change it to use shorts instead of ints.
     */   
    unsigned short cpuset_mem_spread_rotor;
    unsigned short cpuset_slab_spread_rotor;
    int mems_allowed_change_disable;
#else
    int cpuset_mem_spread_rotor;
    int cpuset_slab_spread_rotor;
#endif
#endif

//Control Groups
#ifdef CONFIG_CGROUPS
    /* Control Group info protected by css_set_lock */
    struct css_set *cgroups;
    /* cg_list protected by css_set_lock and tsk->alloc_lock */
    struct list_head cg_list;
#endif

//futex同步機制
#ifdef CONFIG_FUTEX
    struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
    struct compat_robust_list_head __user *compat_robust_list;
#endif
    struct list_head pi_state_list;
    struct futex_pi_state *pi_state_cache;
#endif

//關於內存檢測工具Performance Event
#ifdef CONFIG_PERF_EVENTS
#ifndef __GENKSYMS__
    void * __reserved_perf__;
#else
    struct perf_event_context *perf_event_ctxp;
#endif
    struct mutex perf_event_mutex;
    struct list_head perf_event_list;
#endif

    //非一致內存訪問
#ifdef CONFIG_NUMA
    struct mempolicy *mempolicy;    /* Protected by alloc_lock */
    short il_next;
#endif

    //文件系統互斥資源
    atomic_t fs_excl;   /* holding fs exclusive resources */

    //RCU鏈表
    struct rcu_head rcu;

    /*
     * cache last used pipe for splice
     */

     //管道
    struct pipe_inode_info *splice_pipe;

    //延遲計數
#ifdef  CONFIG_TASK_DELAY_ACCT
    struct task_delay_info *delays;
#endif
#ifdef CONFIG_FAULT_INJECTION
    int make_it_fail;
#endif
    struct prop_local_single dirties;
#ifdef CONFIG_LATENCYTOP
    int latency_record_count;
    struct latency_record latency_record[LT_SAVECOUNT];
#endif
    /*
     * time slack values; these are used to round up poll() and
     * select() etc timeout values. These are in nanoseconds.
     */

     //time slack values,常用於poll和select函數
    unsigned long timer_slack_ns;
    unsigned long default_timer_slack_ns;

    //socket控制消息
    struct list_head    *scm_work_list;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER

    //ftrace跟蹤器
    /* Index of current stored adress in ret_stack */
    int curr_ret_stack;
    /* Stack of return addresses for return function tracing */
    struct ftrace_ret_stack *ret_stack;
    /* time stamp for last schedule */
    unsigned long long ftrace_timestamp;
    /*
     * Number of functions that haven't been traced
     * because of depth overrun.
     */
    atomic_t trace_overrun;
    /* Pause for the tracing */
    atomic_t tracing_graph_pause;
#endif
#ifdef CONFIG_TRACING
    /* state flags for use by tracers */
    unsigned long trace;
    /* bitmask of trace recursion */
    unsigned long trace_recursion;
#endif /* CONFIG_TRACING */
    /* reserved for Red Hat */
    unsigned long rh_reserved[2];
#ifndef __GENKSYMS__
    struct perf_event_context *perf_event_ctxp[perf_nr_task_contexts];
#ifdef CONFIG_CGROUP_MEM_RES_CTLR /* memcg uses this to do batch job */
    struct memcg_batch_info {
        int do_batch;   /* incremented when batch uncharge started */
        struct mem_cgroup *memcg; /* target memcg of uncharge */
        unsigned long bytes;        /* uncharged usage */
        unsigned long memsw_bytes; /* uncharged mem+swap usage */
    } memcg_batch;
#endif
#endif
};

如果需要,可從github處取走註釋源碼:https://github.com/wsy081414/C_linux_practice/blob/master/task_struct.h

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章