进程管理—进程描述符(task_struct)
本文章轉載自:http://blog.csdn.net/qq_26768741/article/details/54348586?locationNum=4&fps=1
前言
 當把一個程序加載到內存當中,此時,這個時候就有了進程,關于進程,有一個相關的叫做進程控制塊(PCB),這個是系統為了方便進行管理進程所設置的一個數據結構,通過PCB,就可以記錄進程的特征以及一些信息。?
 內核當中使用進程描述符task_struct。?
 這個task_struct就是一個定義的一個結構體,通過這個結構體,可以對進程的所有的相關的信息進行維護,對進程進行管理。
接下來我們需要對task_struct結構體當中的成員進行一些分析。
| Linux version 2.6.32-431.el6.i686 | 
1 task_struct
1.1 進程狀態
volatile long state; int exit_state;`
- 1
- 2
- 3
- 1
- 2
- 3
 表示進程的狀態,?
 在進程執行的時候,它會有一個狀態,這個狀態對于進程來說是很重要的一個屬性。進程主要有以下幾個狀態。
 state可能的取值?
 
 
 這些狀態就不再一一說明了,后續進程篇會有專門的說明。
1.2 進程標識符(PID)
pid_t pid; pid_t tgid;
- 1
- 2
- 3
- 1
- 2
- 3
每個進程都有進程標識符、用戶標識符、組標識符,進程標識符對于每一個進程來說都是唯一的。內核通過進程標識符來對不同的進程進行識別,一般來說,行創建的進程都是在前一個進程的基礎上PID加上1作為本進程的PID。為了Linux平臺兼容性,PID一般最大為32767。
1.3 進程內核棧
void *stack
- 1
- 2
- 1
- 2
 stack用來維護分配給進程的內核棧,內核棧的意義在于,進程task_struct所占的內存是由內核動態分配的,確切的說就是內核根本不給task_struct分配內存,只給內核棧分配8KB內存,并且一部分會提供給task_struct使用。?
 task_struct結構體大約占用的大小為1K左右,根據內核版本的不同,大小也會有差異。?
 所以,也就可以知道內核棧最大也就是7KB,否則,內核棧會覆蓋task_struct結構。
1.4 標記
unsigned int flags
- 1
- 2
- 1
- 2
用來反映一個進程的狀態信息,但不是運行狀態,用于內核識別進程當前的狀態,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;
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
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;
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
首先我們要清楚ptrace是什么東西,ptrace是一種提供父進程控制子進程運行,并且可以檢查和改變它的核心image。當trace設置為0時不需要被跟蹤。
1.7 性能診斷工具——Performance Event
#ifdef CONFIG_PERF_EVENTS #ifndef __GENKSYMS__void * __reserved_perf__; #elsestruct perf_event_context *perf_event_ctxp; #endifstruct mutex perf_event_mutex;struct list_head perf_event_list; #endif
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Performance Event是性能診斷工具,這些成員用來幫助它進行分析進程性能問題。
1.8 進程調度
int prio, static_prio, normal_prio;unsigned int rt_priority;
- 1
- 2
- 3
- 1
- 2
- 3
| 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;- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
| 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;
- 1
- 2
- 1
- 2
| 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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
| 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];- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
| 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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
關于信號處理:
| signal | 指向進程信號描述符 | 
| sighand | 指向進程信號處理程序描述符 | 
| blocked | 表示被阻塞信號的掩碼 | 
| pending | 存放私有掛起信號的數據結構 | 
| sas_ss_sp | 信號處理程序備用堆棧的地址 | 
1.13 文件系統信息
//文件系統信息結構體 /* filesystem information */struct fs_struct *fs;//打開文件相關信息結構體 /* open file information */struct files_struct *files;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
進程可以用來打開和關閉文件,文件屬于系統資源,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_CTXSWint 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_TRACEunsigned int btrace_seq; #endif//進程調度策略相關的字段unsigned int policy;cpumask_t cpus_allowed;//RCU同步原語 #ifdef CONFIG_TREE_PREEMPT_RCUint 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 lockit 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_AUDITSYSCALLuid_t loginuid;unsigned int sessionid; #endifseccomp_t seccomp;#ifdef CONFIG_UTRACEstruct 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_IRQFLAGSunsigned 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 48ULu64 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_CPUSETSnodemask_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; #elseint 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_FUTEXstruct robust_list_head __user *robust_list; #ifdef CONFIG_COMPATstruct compat_robust_list_head __user *compat_robust_list; #endifstruct list_head pi_state_list;struct futex_pi_state *pi_state_cache; #endif//關于內存檢測工具Performance Event #ifdef CONFIG_PERF_EVENTS #ifndef __GENKSYMS__void * __reserved_perf__; #elsestruct perf_event_context *perf_event_ctxp; #endifstruct mutex perf_event_mutex;struct list_head perf_event_list; #endif//非一致內存訪問 #ifdef CONFIG_NUMAstruct 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_ACCTstruct task_delay_info *delays; #endif #ifdef CONFIG_FAULT_INJECTIONint make_it_fail; #endifstruct prop_local_single dirties; #ifdef CONFIG_LATENCYTOPint 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 };
總結
以上是生活随笔為你收集整理的进程管理—进程描述符(task_struct)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 分词之后的如何做特征选择_特征选择怎么做
- 下一篇: Unity开发游戏时可以用到的一些插件介
