Brief analysis of TASK_STRUCT structure body

Source: Internet
Author: User
Tags bit set current time signal handler terminates volatile

The content of this article is summarized:
1. The concept of the process
2. Process Control block
3. Analyze the pcb-task_struct under Linux

Speaking of Task_struct, perhaps you are very unfamiliar. If I were to say that he was a structure of the PCB definition of Process control block under Linux, you might know that. The following topics begin to share today: 1. The concept of the process:

When it comes to process Control block PCB, have to say the process. In the previous operating system curriculum learning, the definition is given: the process is a dynamic process of execution of the program. (So, you really can figure it out.) The concept is indeed more abstract, anyway, I was not very clear before the study. Process = Program Segment + data segment + Process control block. When I learned the process of operating system again, there was a deeper understanding:

From the level of the operating system: a process is an execution instance of a program; a process is an executing program; a process is an entity that can assign a processor and execute by a processor. So, without the program being executed, it must not be a process. No. If in a single processor system, only one process can be executed at a time (that is, only one process can be running at a time), then other programs that are loaded into memory (which have acquired all the resources except the processor) are also processes.
From the kernel level: serves as an entity that allocates system resources (including memory, and so on).
The two basic elements of a process are program code (which can be shared by other processes) and the dataset associated with the code. In fact, this is the same as "process = Program Segment + data segment + Process Control block". A dataset refers to data segments and process control blocks. 2. Process Control BLOCK:

In order to describe the process information, we introduced the process control block this data structure. So why do you need a Process control block? How it works.
In a single processor system, we can only perform one process at a time, how we know which process is executing. What processes need to be executed after the process has been executed. If a process needs to be interrupted (not killed) for a variety of reasons, then how do we know where to go before the process is executed (impossible to start from scratch), and so on, so that the process control block is required.
By analyzing all the above, we can conclude that: the Process Control block should at least contain the process identity (the unique identification of the process, the PID), the priority of the process, the context information for the process, the address of the next instruction in the process, the address of the program in the process, and so on (the following will give the Task_ A member of a struct structure).
When the operating system to dispatch a process to execute, the process from the PCB to query the priority and current state of the process;
When the system scheduling to a process, according to the existing information stored in the PCB to reply to the scene first, and then to modify the status of the process, according to the program's address, find the location of the program, and start execution;
When a process needs to be paused for a reason, the current state must be saved in the PCB and the address of the next instruction is recorded.
It is obvious that the process control block plays a very important role in the whole process of execution. Below we will analyze the Linux pcb-task_struct structure. 3. Analyze the pcb-task_struct under Linux

The definition of task_struct is located in the/usr/include/linux/sched.h file (centos6.5).
Below I classify the data members in the structure body:

(1) Status of the process:
Whether a process is running or sleeping or blocking will be described in the members below.
volatile long state;
The possible values for state are:

#define Task_running        0//process is either executing, or preparing to perform
#define TASK_INTERRUPTIBLE  1//interruptible sleep, which can be awakened by a signal
#define Task_uninterruptible    2//non-interrupted sleep, can not be awakened by signal
#define __TASK_STOPPED      4//process stops executing
#define __task_ Traced       8//process is tracked/
* in Tsk->exit_state/ 
#define Exit_zombie     16/Zombie state process, which indicates that the process was terminated, but the parent process has not       have access to its termination information, such as whether the process has been executed or not.                     
#define Exit_dead       32//The final state of the process, the process dies. /
* in Tsk->state again/* 
#define TASK_DEAD       64//Death
#define Task_wakekill       128//Wake up and kill process c20/> #define TASK_WAKING     256//Wake up process 

(2) Unique identification of the process

Unique identification of the pid_t pid;//process the value of the
 PID member of the lead thread of the pid_t tgid;//thread Group

PID is the only representation of the process, the scope is 0~32767, can represent 32,768 processes.
In a Linux system, all threads of a thread group use the same PID as the thread group's lead thread and are stored in the Tgid member. (a thread is the smallest unit in which a program runs, and a process is the basic unit of the program.) )

(3) kernel stack of process

void *stack;//is used to maintain the kernel stack of a process.

The Linux kernel represents the kernel stack of a process through the following structure body:

Union thread_union {
    struct thread_info thread_info;
    unsigned long stack[thread_size/sizeof (long)];

Note: About the kernel stack, and then to add.

(4) Marking of the process:

unsigned int flags; Process Flag Information #define PF_ALIGNWARN 0x00000001/* Print Alignment WARNING MSGS *//Not implemented Yet, only for 486*/#define PF_STARTING 0x00000002/* Being created/#define PF_EXITING 0x00000004/* gettin    G Shut down */#define Pf_exitpidone 0x00000008/* pi exit done on shut down * * * * #define PF_VCPU 0x00000010 /* I ' m a virtual CPU * * * #define PF_FORKNOEXEC 0x00000040/* forked but didn ' t exec/#define PF_MCE_PROCESS 0x000 00080/* Process policy on MCE errors/#define PF_SUPERPRIV 0x00000100/* Used super-user * * #defi NE pf_dumpcore 0x00000200/* Dumped core/#define PF_SIGNALED 0x00000400/* killed by a signal */#define PF _memalloc 0x00000800/* Allocating memory * * #define PF_FLUSHER 0x00001000/* Responsible for disk writeback * /#define PF_USED_MATH 0x00002000/* If unset the FPU must be initialized before use */#define pf_freezing 0x000 04/* Freeze in progress.    Do don't account to load */#define PF_NOFREEZE 0x00008000/* This thread should is not frozen * * * #define Pf_frozen 0x00010000/* Frozen for system suspend/#define Pf_fstrans 0x00020000/* Inside a filesystem transaction * * Define PF_KSWAPD 0x00040000/* I am KSWAPD * * #define PF_OOM_ORIGIN 0x00080000/* Allocating much of memory to OT    Hers * * #define PF_LESS_THROTTLE 0x00100000/* throttle me less:i clean memory/#define PF_KTHREAD 0x00200000 /* I am a kernel thread */#define PF_RANDOMIZE 0x00400000/* RANDOMIZE virtual address spaces/#define Pf_swapwrit  E 0x00800000/* allowed to write to swap */#define PF_SPREAD_PAGE 0x01000000/* spread PAGE cache over Cpuset * * #define PF_SPREAD_SLAB 0x02000000/* Spread some slab caches over Cpuset/#define Pf_thread_bound 0/* Thread bound to specific CPU */#define PF_MCE_EARLY 0x08000000/* EARLY Kill for MCE process policy * * #define PF_MEMPOLICY 0x10000000/* non-default NUMA mempolicy/#define Pf_mutex_tester 0x20000000/* THR EAD belongs to the RT Mutex tester/#define PF_FREEZER_SKIP 0x40000000/* Freezer not count it as should
 E */#define PF_FREEZER_NOSIG 0x80000000/* Freezer won ' t send signals to it * *

(5) Kinship between processes:

struct Task_struct *real_parent;  /* Real parent process
    /struct task_struct *parent/* recipient of SIGCHLD, WAIT4 () reports * * 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 * *

Real_parent points to its parent process, and if the parent process that created it no longer exists, it points to the Init process with PID 1.
Parent points to its parent process, and when it terminates, it must send a signal to its parent process. Its value is usually the same as real_parent.
Children represents the head of a linked list, and all elements in a linked list are its child processes (the process's child process list).
The sibling is used to insert the current process into the sibling list (the sibling list of the process).
Group_leader the lead process that points to the group of processes in which it resides.

(6) Process scheduling information:

   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;
   unsigned int policy;

Static_prio is used to save static precedence, which can be modified by the nice system call.
Rt_priority is used to save the real-time priority.
The value of the Normal_prio depends on the static priority and the scheduling policy.
Prio is used to save dynamic precedence.
Policy represents the scheduling strategy of the process, currently has the following five kinds:

#define Sched_normal        0//is scheduled according to priority (in some places it is the CFS scheduler)
#define SCHED_FIFO        1//FIFO scheduling algorithm
#define SCHED_RR        scheduling algorithm of 2//time slice rotation
#define Sched_batch        3//process for non-interactive processor consumption
#define SCHED_IDLE        5//system with low load
#define Sched_reset_on_fork     0x40000000

(7) Time data member:

cputime_t Utime, Stime, utimescaled, stimescaled;
    cputime_t Gtime;
    cputime_t Prev_utime, prev_stime;//record current run time (user state and kernel state)
    unsigned long NVCSW, NIVCSW;//voluntary/involuntary context switch count
    struct Timespec start_time;  Process start execution time    
    struct timespec real_start_time;  Process real start execution time
    unsigned long min_flt, Maj_flt;
    struct Task_cputime cputime_expires;//cpu execution effective time
    struct List_head cpu_timers[3];//is used to count the time
    that a process or process group is tracked by a processor struct List_head run_list;
    unsigned long timeout;//The current time used (the difference from the start time)
    unsigned the size of the time slice of the int time_slice;//process
    int nr_cpus_allowed;

Note: With respect to the start time of the process and the real start of execution time, I think that the process obtains all the resources except the processor, and it enters the ready state, which is the time when the process begins to execute, that is, when the memory is entered. And the real start time is the time when the processor begins to execute. This is my understanding.

(8) Signal processing information

struct Signal_struct *signal;//point to the process signal descriptor
    struct Sighand_struct *sighand;//to the process signal Handler descriptor
    sigset_t blocked, real_blocked;//blocking signal masking
    sigset_t saved_sigmask;    /* restored if Set_restore_sigmask () was used/
    struct sigpending pending;//a signal to be processed on the process
    unsigned long sas_ss_sp //Signal handler alternate stack address
    size_t sas_ss_size;//address of the stack of signal handlers

(9) File system Information

/* FileSystem information */
    struct fs_struct *fs;//file system Information pointer/
* Open File information/
    struct FILES_ struct *files;//information pointer to open file

The following is a definition and comment on task_struct:

 struct Task_struct {volatile long state;  Describes whether the process can be executed, or interruptible, etc. unsigned long flags;    Flage is the process number, and an int sigpending is given when the fork () is invoked; Whether the process is pending signal mm_segment_t Addr_limit; Process address space, distinguishing between kernel processes and normal processes in memory storage locations//0-0XBFFFFFFF for User-thead//0-0xfffffff
F for Kernel-thread//dispatch flag, which indicates whether the process needs to be scheduled again, if it is not 0, then the dispatch volatile long need_resched occurs when returning from the kernel state to the user state;  int lock_depth;       Lock depth long nice;
Process of the basic time slice//process scheduling strategy, there are three kinds of real-time process: SCHED_FIFO,SCHED_RR, time-sharing process: sched_other unsigned long policy; struct Mm_struct *mm;
Process memory management information int processor;
If the process is not running on any CPU, the value of cpus_runnable is 0, otherwise it is 1 the value is updated unsigned long cpus_runnable when the queue is locked, cpus_allowed; struct List_head run_list;  Pointer to run queue unsigned long sleep_time;
The sleep time of the process is used to connect all the processes in the system into a two-way cyclic list, the root of which is init_task struct task_struct *next_task, *prev_task;
struct Mm_struct *active_mm;       struct List_head local_pages;
Point to local page unsigned int allocation_order, nr_local_pages;  struct LINUX_BINFMT *binfmt; The format of the executable file that the process runs in intExit_code, exit_signal;     int pdeath_signal;
A signal sent to a subprocess when the parent process terminates unsigned long personality; 
Linux can run IBCS2-compliant program int did_exec:1 generated by other Unix operating systems;    pid_t pid;   Process identifier, which is used to represent a process pid_t pgrp;  Process group identification that represents the process group pid_t TTY_OLD_PGRP to which the process belongs;  The group identifier of the Process control Terminal pid_t session;
Session identification of the process pid_t tgid;     int leader;
Indicates whether the process is the session manager struct Task_struct *p_opptr,*p_pptr,*p_cptr,*p_ysptr,*p_osptr;   struct List_head thread_group; Line Cheng struct task_struct *pidhash_next;
Used to link a process into a hash table struct task_struct **pidhash_pprev;  wait_queue_head_t Wait_chldexit;  For WAIT4 () using struct completion *vfork_done; For vfork () using unsigned long rt_priority; Real-time priority, using it to calculate real-time process scheduling of the weight value//IT_REAL_VALUE,IT_REAL_INCR for real timer, unit for jiffies, the system according to It_real_value//set timer of the first termination time.
When the timer expires, send the SIGALRM signal to the process, at the same time, according to//IT_REAL_INCR reset termination time, IT_PROF_VALUE,IT_PROF_INCR for profile timer, unit for jiffies.
When the process runs, no matter in what state, each tick makes the It_prof_value value minus one, and when it is reduced to 0 o'clock, send//signal sigprof to the process and reset the time according to IT_PROF_INCR. It_virt_value,it_virt_value is used for the virtual timer, the unit is jiffies. When the process is running, no matter in what//state, each TIck the It_virt_value value minus one when it's reduced to 0 o'clock, sending a signal to the process SIGVTALRM, resetting the initial value according to//IT_VIRT_INCR.
unsigned long it_real_value, It_prof_value, It_virt_value;
unsigned long it_real_incr, IT_PROF_INCR, It_virt_value;   struct Timer_list real_timer;      Pointer to real-time timer struct TMS times;  Record the time consumed by the process unsigned long start_time; 
Process creation time//record the user state time consumed by the process on each CPU and the kernel mentality time long per_cpu_utime[nr_cpus], Per_cpu_stime[nr_cpus]; Memory page faults and exchange information://min_flt, Maj_flt Cumulative process of the number of secondary pages (Copy on write and anonymous pages) and the number of main page faults (from the mapping file or Exchange//device read the number of pages), Nswap record process cumulative number of pages,
That is, the number of pages written to the swap device.
Cmin_flt, Cmaj_flt, Cnswap records the cumulative number of page faults in the process for all descendants of the ancestors, the number of main pages and number of pages swapped out.
When the parent process reclaims aborted child processes, the parent process accumulates this information for the child process into these domains of its own structure unsigned long min_flt, Maj_flt, Nswap, Cmin_flt, Cmaj_flt, Cnswap; int swappable:1; Indicates whether the virtual address space of the process is allowed to be swapped//process authentication information//uid,gid The user identifier and group identifier of the user running the process, usually the Uid,gid//euid,egid of the process creator as valid Uid,gid//fsuid,
Fsgid for file system Uid,gid, these two ID numbers are usually equal to valid uid,gid, and they are used when checking access rights to files//systems.
Suid,sgid for backup Uid,gid uid_t Uid,euid,suid,fsuid;
gid_t Gid,egid,sgid,fsgid; int ngroups; Record how many user groups the process gid_t groups[ngroups]; Record the group where the process is located//The power of the process, respectively, is a set of valid bits, a set of inherited bits, the allowable bit set kernel_cap_t cap_effective, cap_inheritable, cap_permitted;
int keep_capabilities:1;
struct User_struct *user;  struct Rlimit rlim[rlim_nlimits];   Resource restriction information associated with the process unsigned short used_math;   Whether to use the FPU char comm[16];
The process is running executable file name//file system Information int link_count, total_link_count;
Null if no TTY process is located in the control terminal, if you do not need to control the terminal, then the pointer is empty struct tty_struct *tty;
unsigned int locks;  Inter-process communication information struct Sem_undo *semundo; The process of all undo operations on the signal lights struct sem_queue *semsleeping;
  When a process is suspended because of a semaphore operation, he records the CPU state of the pending operation//process in the queue, and when switching, save to the task_struct of the stop process struct thread_struct thread;
  File system Information struct fs_struct *fs;
  Open file information struct files_struct *files;
Signal processing function spinlock_t Sigmask_lock; struct Signal_struct *sig;  Signal processing function sigset_t blocked;  The process is currently blocking the signal, each signal corresponding to a struct sigpending pending;
Whether the signal to be processed on the process is unsigned long sas_ss_sp;
size_t Sas_ss_size;
Int (*notifier) (void *priv);
void *notifier_data;
sigset_t *notifier_mask;
U32 parent_exec_id;

U32 self_exec_id;
spinlock_t Alloc_lock; void *journal_Info
 };

Note: The scheduling strategy of the process is: first come first service, short job first, time slice rotation, high response ratio priority and so on scheduling algorithm.

The above reference documents and books:
1.task_struct source code and the annotation section, originates from
http://blog.csdn.net/lf_2016/article/details/54347820
2. Reference books:
"Computer operating system (third edition) Tang Xiaodan"
Other content refers to the following connections:
http://blog.csdn.net/npy_lp/article/details/7292563

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.