This article is original, reprint please specify: http://www.cnblogs.com/tolimit/
Recently in retrospect some knowledge point, feel to the process this piece is somewhat vague, specially writes an essay to the process information to consolidate and review.
Procedures and processes
My personal understanding is that a program is a binary code or even a simple executable file, and when the program's binary code is put into memory, it produces one or more processes.
CPU time slices
For the CPU, its job is to keep executing instructions, and because the CPU executes instructions very quickly, it can spend 5ms of time dedicated to the execution process a,5ms time dedicated to the execution process b,5ms time dedicated to the execution process C, and then the execution of processes A, B, C. It seems to us that processes a, B, and C are executed at the same time, while only one process is actually running on the CPU at the same point.
Process Descriptor
Is the structure used to describe a process, each process has only one process descriptor, which contains all the information related to the process.
structtask_struct {.../*process Status*/ volatile LongState ; /*point to Kernel stack*/ void*Stack; /*used to join the process chain list*/ structlist_head tasks; ...... /*The memory area descriptor that points to the process*/ structMm_struct *mm, *active_mm; ........ /*process ID, PID is different for each process (thread)*/pid_t pid; /*Thread group ID, the same thread group has the same PID, and the lead thread (the first lightweight process in the group) PID, saved in Tgid, thread group lead thread PID and tgid the same*/pid_t Tgid; /*used to connect to the PID, Tgid, PGRP, session hash table*/ structPid_link Pids[pidtype_max]; ........ /*Point to the parent process that created it, and if its parent process does not exist, point to the Init process*/ structTask_struct __rcu *real_parent; /*points to the current parent process, usually consistent with real_parent*/ structTask_struct __rcu *parent; /*Child process Chain list*/ structList_head Children; /*Brother process Chain list*/ structlist_head Sibling; /*Thread group lead thread pointer*/ structTask_struct *Group_leader; /*Save the hardware context while the process is switching (the hardware context is saved altogether in 3 places: TSS (save kernel stack address, IO permission bit), Thread_struct (save most CPU register values), kernel stack (save eax,ebx,ecx, Common register values such as edx))*/ structthread_struct thread; /*current directory*/ structFs_struct *FS; /*point to the file descriptor, and all open files in this process are in an array of pointers in this area.*/ structFiles_struct *files; ... ../*A signal descriptor used to track a shared pending signal queue, shared by all processes that belong to the same thread group, that is, the thread of the same threads group this pointer points to the same signal descriptor*/ structSignal_struct *signal; /*Signal Processing function Descriptor*/ structSighand_struct *Sighand; /*sigset_t is an array of bits, each of which corresponds to a bit, and the maximum number of signals in Linux is * blocked: Blocked signal mask * real_blocked: temporary mask for blocked signals*/sigset_t blocked, real_blocked; sigset_t Saved_sigmask; /*restored if Set_restore_sigmask () was used*/ /*private suspend signal queue*/ structsigpending pending; ........}
This section only intercepts the fields that need to be explained later. In the kernel, there will be a list of processes linked to the process chain of all processes by using the tasks structure in the process descriptor.
Process Kernel Stack
We know in the programming time that there is a stack in the process address space for the program to execute smoothly, and when the program falls into the kernel state, it is not able to use the stack of the application state, so for each process it also has a kernel-state stack in the kernel, in the kernel, the stack and the Thread_info (thread descriptor) Structures together, this storage area is typically 8192 bytes, or two page boxes. The THREAD_INFO structure size is 52 bytes, which means that the available stack size for the process is 8,140 bytes. This 8K kernel stack is sufficient because the process needs to execute a lot of code in the kernel state. You can also set the entire kernel stack to a page box size (4KB) when compiling the kernel, but in this case the kernel does not use the kernel stack of the process when processing hard interrupts and soft interrupts, but instead uses the additional two stacks: the Hard interrupt request stack (one per CPU, size 4K), and the soft interrupt request stack (one per CPU) , size 4K). It is important to note, however, that the kernel stack of the process is still used for exception handling.
As can be seen, the kernel stack of the process is growing downward, that is, the bottom of the stack at the high address, stack top in the low address. For the purpose of this kernel stack, we can summarize:
- The process falls into the kernel and is used instead of the stack area of the application layer.
- Interrupts occur when the process context is saved and used to interrupt nested field saves and returns.
- When a process switch occurs, the value of the partial register is saved in the kernel stack of the process.
- Some important fields are stored in thread_info to maintain the normal operation of the process.
Lightweight process
Linux uses lightweight processes to support multithreaded applications, in fact, it is created based on the fork () system call, but only in the initialization of the process descriptor is different. First, the lightweight process is also a process, it has its own PID, its own kernel stack and process descriptor, and even its own scheduling policy, and the lightweight process differs from the normal process is that it does not have its own process address space, and to respond to the signal received by other threads in the thread group ( However, some signals can be masked by modifying the signal shielding Word. The lightweight process uses the memory address space of the parent process, that is, the MM and active_mm pointers in the task_struct structure point to the address indicated by the MM pointer of the parent process. The signal descriptor pointer, signal, points to the address that the parent process points to. And in the application layer, the thread has its own stack, I think this should be implemented by GLIBC.
Lightweight processes and common process differences:
- Without its own process address space, use the parent process's process address space
- Share signals with all processes in the group
Process status
- task_running: the operational state in which the process executes either on the CPU or is ready to execute.
- task_interruptible: an interruptible wait state in which a process is suspended (sleep) until a condition is true, resulting in a hard interrupt, freeing the system resources that the process is waiting for, or passing a signal that is a condition that can wake the process.
- task_uninterruptible: A non-interruptible wait state similar to an interruptible wait state, except that it cannot be awakened by a signal. It is used in some special cases, for example: When a process opens a device file, the device driver will use this state when it starts probing for the appropriate hardware.
- task_stoped: paused state when the process receives a sigstop, SIGTSTP, sigttin, or Sigttou signal to enter.
- task_traced: trace status, Process execution is paused by the debugger program, and when one process is monitored by another process, any signal can place the process in task_traced state.
There are also two states that can be stored either in the state field of the process descriptor or in the Exit_state field. As you can see from these two fields, the state of the process is only one of these two states when the process execution is terminated:
- Exit_zombie: Zombie State, the process will be terminated, but the parent process has not yet released the WAIT4 () or waitpid () system called to return information about the death process. Before releasing the wait () class system call, the kernel cannot discard the data contained in the dead process descriptor because the parent process may also need it.
- Exit_dead: zombie undo State, the final state after the process is terminated, the kernel deletes this process descriptor after the parent process publishes the WAIT4 () or waitpid () system call.
For a normal process, its execution status is as follows:
We use a simple example to illustrate the transition of this state, and we have a program a that works by doing some calculations and then writing the computational structure to a disk file. We run it in the shell, at first it is the task_running state, that is, the runtime, the CPU will continue to allocate time slices for our process A to run, each time the chip is exhausted, process a will transition to the ready state (in fact, the task_running state, Just waiting for the CPU to allocate the time slice, temporarily not running on the CPU). When process a uses fwrite or write to write data to the disk file, it enters the blocking state (task_interruptible state), and after the disk writes the data, it tells the kernel through an interrupt, and the kernel then blocks the state of process a from the blocked state (task_ interruptible) transition to Ready State (task_running) waits for the CPU to allocate the time slice to run. And finally, when process a needs to exit, the kernel first sets it to a zombie state (Exit_zombie), when the memory it uses has been freed, leaving only a process descriptor for use by the parent process, and finally when the parent process (that is, the shell we started it at first) through Wait () After a class system call notifies the kernel, process A is set to a zombie revocation state (Exit_dead) and its process descriptor is released. The entire run cycle of process A is completed.
PID and Tgid Fields
A PID is a number that identifies a process, just like the student's number, and each process has a unique number that is stored in the PID field of the process descriptor. Generally, during the system operation, the PID is sequentially numbered, such as the PID of process A is 10, the next process to create the PID is 11. However, the PID value has an upper limit, when the core used by the PID reached this limit will cycle start to find the small number of idle PID. In the default state, the maximum PID value is 32767 (pid_max_default-1), and the PID upper limit can be reduced by modifying the/proc/sys/kernel/pid_max file. In 64-bit systems, the PID can be extended to 4194303.
The kernel uses a bitmap called Pidmap to manage the assigned PID number and the idle PID number. In a 32-bit system, the size of the Pidmap is a page box size (4KB), and a page box size of 32,768 bits, that is, each bit represents a PID number, 1 means that the PID has been assigned, 0 means that the PID number is not used, and under the 64-bit system, PIDMAP will use more than one page box.
In the POSIX standard, it is stipulated that all threads in a multithreaded application must have the same PID, and in the Linux kernel, it is the function of using lightweight processes to implement threads, but the lightweight process is also a process, their PID is different, in order to achieve this, The kernel introduces the Tgid field in the process descriptor. In the thread group concept of Linux, all threads in a thread group use the same PID as the thread group leader thread, the PID of the first lightweight process in the group, and are saved to the Tgid field in the process descriptor, such as:
In the programming process, the value returned by the Getpid () function that we use is actually the tgid of the current process instead of the PID value, and because the lead thread in the thread group is the same as the PID and Tgid, Getpid () has the same role as the general process for such a process.
Let's talk about how the kernel organizes all of the PID and process descriptors together to make it easier for the system to find and use. While the system is running, hundreds or thousands of processes may be running, when the process's lookup efficiency is critical, such as when the system administrator uses the kill 1024 command to terminate the pid=1024 process, the kernel will export the corresponding process descriptor from this PID for processing. To improve the search efficiency, the kernel uses 4 hash tables specifically for indexing process descriptors. Why 4, because we can use PID, Tgid, PGRP, session to find the process, these hash tables are described as follows:
In the kernel, the four hash tables accounted for 16 page boxes, that is, each hash table accounted for 4 page boxes, each of them can have 2048 table entries, the kernel will put the address of the four hash table in the Pid_hash array. Now the problem, take the PID hash table for example, how to save 32,767 PID values in 2048 table entries, in fact, the kernel will be assigned to each of the PID value of a processing, the resulting value is the corresponding table entries, the same processing results of the same PID is strung into a linked list, as follows:
When we use the Kill 29384 command, the kernel will process 199 according to 29384, then take 199 as subscript, get the corresponding list header in the PID hash table, and find out the pid=29384 process in this list. The process descriptor uses a struct pid_link Pids[pidtype_max] to link into these four hash tables. For the other three hash tables, the truth is the same.
Inter-process relationships
In the system, in addition to process 0, a process is created by another process that has a parent-child relationship. If a process creates multiple child processes, there is a sibling relationship between the child processes. During the whole system startup, the first process of the system is initialized Init_task, which is a process in the kernel, it is the ancestor of all processes, then it will start the PID 1 init process and PID 2 Kthreadd, the two processes started after all processes, The init_task is then converted to an idle process to run when the CPU is idle. In the process descriptor, using the real_parent, parent, children, and sibling pointers to organize the process relationships together, let's look at the descriptions of these pointers:
And if a process P0 creates processes P1, P2, P3, the process P3 creates the process P4, the whole list is like this
Organizational processes
All processes in the task_running state are placed in the CPU's run queue, which is likely to be in a different CPU running queue.
The system does not have a dedicated list of processes for task_stoped, Exit_zombie, and Exit_dead states, because process access in these states is relatively straightforward and can be accessed through PID and through a list of child processes in a particular parent process.
All task_interruptible and task_uninterruptible are put into the corresponding waiting queue, there are many waiting queues in the system, some are waiting for the termination of the disk operation, some are waiting to release the system resources, some are waiting time through a fixed interval, Each waiting queue has a different wake-up condition, such as waiting for queue 1 to wait for the system to release resource A, while waiting for queue 2 to wait for the system to release resource B. Therefore, the wait queue represents a set of sleep processes, and when a condition is true, the kernel wakes up the process on the waiting queue. Let's look at a simple sleep_on () function in the kernel:
/*Wq is a queue header for a waiting queue*/voidSLEEP_ON (wait_queue_head_t *Wq) { /*declaring a wait queue node*/wait_queue_t wait; /*initializes the wait queue node with the current process.*/Init_waitqueue_entry (&wait, current); /*set the current process status to Task_uninterruptible*/ Current->state =task_uninterruptible; /*Add this waiting queue node representing the current process to the Wq waiting queue .*/Add_wait_queue (Wq,&wait); /*The request Scheduler is dispatched, and the process is removed from the CPU run queue after the schedule is executed, and only after waiting for the queue to wake up to the CPU run queue*/schedule (); /*here the process has been waiting for the queue to wake up and move back to the CPU run queue, that is, the waiting condition is true, and the first thing to wake up is to remove itself from the waiting queue Wq*/Remove_wait_queue (Wq,&wait); }
At this point, there is another problem, such as waiting queue is waiting for the system to release resource A, and waiting for all the processes in the queue to be able to take possession of this resource A, like the amount of semaphores we have programmed, this time the system is not to wake up all the processes in this wait queue, but only wake one. The kernel distinguishes this mutex process from the principle that all of the waiting queue nodes in the wait queue wait_queue_t flags are set to 1 (the default is 0).
Linux Source Analysis-process