First assignment: Deep source analysis process model based on Linux system

Source: Internet
Author: User
Tags prev

1. Preface

This paper is mainly based on the Linux 2.6 source code Analysis process model. Source code: Https://elixir.bootlin.com/linux/v2.6.39/source

2. Process

Definition: A process is a computer program on a data set on a running activity, the system is the basic unit of resource allocation and scheduling, is the basis of the operating system structure.

Organization of 3.Linux system processes

Process is composed of process control block (PCB), program segment, data section.

3.1 Process Control block

Process Control blocks (processing control block), is a data structure in the core of the operating system, mainly represents the process state, is the system in order to manage the process of setting up a specialized database. In Linux, this structure is called task_struct. Task_struct is defined in the/include/linux/sched.h.

Source Code Address

PCB Contains information:

    • Process identifiers: Each process must have a unique identifier
      // Unique identification of the process // The value of the PID member of the thread group's lead thread
    • Process status
      volatile long State;
    • Process priority
      intint rt_priority;

      Prio represents the dynamic priority of a process, Static_prio represents the static priority of the process, Normal_prio represents the priority calculated based on the static priority of the process and the scheduling policy, and rt_priority represents the priority of the real-time process.

    • CPU Field Protected Area
    • Process corresponding program and data address
    • Process resource List
    • Signal Processing Information
    • Information about the file system
    • Additional information related to the process
3.2 Program Segments

Program segment: program code executed by CPU

3.3 Data Segments

Data segment: The result of the original data or program execution after the process corresponds to the program.

Status of processes in 4.Linux systems and Transitions 4.1 status of processes
    • Three basic states of the process:

Run state (the moment the process actually consumes the CPU)

Ready state (can be run, but temporarily stopped because other processes are running)

Blocking state (the process cannot run unless an external event occurs)

    • In a Linux system, the status of the process is defined in the/include/linux/sched.h in the following ways.

Source code Address: https://elixir.bootlin.com/linux/v2.6.37/source/include/linux/sched.h#L182

#defineTask_running 0//executable State#defineTask_interruptible 1//interruptible sleep Status#defineTask_uninterruptible 2//non-disruptive sleep state#define__task_stopped 4//paused State#define__task_traced 8//Tracking Status/*In tsk->exit_state*///Termination Status#defineExit_zombie 16#defineExit_dead 32
Task_running is a ready state, and the process is currently only waiting for CPU resources.
Both task_interruptible and task_uninterruptible are blocking states, and the process is currently waiting for other system resources other than the CPU, which can be awakened by the signal, which is not available.
Zombie is a zombie process and the process has finished running, but the process control block has not been logged off.
The task_stopped is a pending state and is used primarily for debugging purposes. When the process receives the sigstop signal, it enters the state and resumes operation after receiving the Sigcont.
4.2 Creation of the process

In Linux, the fork (), Vfork (), Clone () three process creation methods are mainly provided.

You can use fork () to create a process in a Linux system, and the fork () function is used to create a new process from an existing process. The new process is a child process, and the original process is the parent process. Using the fork () function to get a child process is a replica of the parent process, which inherits the entire process's address space from the parent process, including the process context, code snippet, process stack, memory information, file descriptor, signal control setting, process priority, process group number, current working directory, root directory, Resource constraints and control terminals, and the child process is unique only its process number, resource usage and timers, such as child processes are almost full replication of the parent process, so the parent-child process runs a program at the same time. The Vfork () function copies only the task_struct and kernel stacks.

4.3 Transitions of the state

The process state transition diagram looks like this:

1. The process is blocked because it waits for input

2. Scheduler selects another process

3. Scheduler chooses this process

4. Valid input appears

5. End of process

4.4 Termination of the process
    • Normal exit
    • Error exiting
    • Critical Error
    • Killed by another process
5. Scheduling of processes

When the computer system is a multi-channel program design systems, there will usually be more than one process through the competition CPU. This happens as long as two or more processes are in the ready state. If only one CPU is available, you must select the next process to run. The part that completes the selection work is called scheduling, and the algorithm used is called the scheduling algorithm.

5.1 When to dispatch

A key issue with scheduling is when scheduling decisions are made.

    • After you create a new process, you need to decide whether to run the parent process or run the child process. Both of these processes are in a ready state and can be arbitrarily determined.
    • A scheduling decision must be made when a process exits. Selecting a process from the ready process, if there is no ready process, typically runs a system-provided idle process.
    • When a process blocks on I/O and semaphores or is blocked for other reasons, you must select another process to run.
    • When an I/O interrupt occurs, a scheduling decision must be made.

5.2 How to dispatch

Schedule (): The Process scheduler function, which completes the scheduling of the process. The main flow of this function is to close the kernel preemption first, locate the ready queue on the current CPU, check the status of the Prev, and if it is non-operational, and is not preempted in the kernel, it is removed from the queue rq. However, if the prev has a pending signal, set its status to Task_running state and remain in the queue rq. Then pick the next high-priority process, and notify the scheduler to switch, update the queue to save the process information, and finally notify the scheduling class to complete the process switch.

Source code Address: HTTPS://ELIXIR.BOOTLIN.COM/LINUX/V2.6.39/SOURCE/KERNEL/SCHED.C

Asmlinkagevoid__sched Schedule (void){    structTask_struct *prev, *next;//the structure of the current process, the next processUnsignedLong*switch_count;//number of process switches    structRQ *rq;//Ready Queue    intcpu;need_resched:preempt_disable (); //Turn off kernel preemptionCPU = smp_processor_id ();//Locate the ready queue on the current CPU RQRQ =Cpu_rq (CPU);    Rcu_note_context_switch (CPU); Prev= rq->curr;//Save the running process to the PrevSchedule_debug (prev); if(Sched_feat (Hrtick)) hrtick_clear (RQ); RAW_SPIN_LOCK_IRQ (&rq->Lock); Switch_count= &prev->nivcsw;//Switch Count record    if(Prev->state &&!) (Preempt_count () & preempt_active)) {//the current process is non-operational and non-kernel preemption               if(Unlikely (Signal_pending_state (Prev->state, prev))) {//set process to ready state if not a non-pending signalPrev->state =task_running; } Else{//if it is a non-pending signal, it is removed from the queue            /** If A worker is going to sleep, notify and * ask Workqueue whether it wants to wake up a  * Task to maintain concurrency.             If So, wake * the task. */            if(Prev->flags &Pf_wq_worker) {                structTask_struct *To_wakeup; To_wakeup=wq_worker_sleeping (prev, CPU); if(To_wakeup) try_to_wake_up_local (to_wakeup);            } deactivate_task (RQ, Prev, dequeue_sleep); /** If We were going to sleep and we had plugged IO queued, make * sure to submit it to avoid D             Eadlocks. */            if(Blk_needs_flush_plug (prev)) {Raw_spin_unlock (&rq->Lock);                Blk_schedule_flush_plug (prev); Raw_spin_lock (&rq->Lock); }} Switch_count= &prev->NVCSW; } pre_schedule (RQ, prev); //notifies the scheduler that a process switch is about to occur    if(Unlikely (!rq->nr_running))    Idle_balance (CPU, RQ); Put_prev_task (RQ, prev); //notifies the scheduler that the current process will be replaced with another processNext = Pick_next_task (RQ);//pick a task to runClear_tsk_need_resched (prev);//clears the Pre tif_need_resched flagRq->skip_clock_update =0; if(Likely (prev! = next)) {//if not the same processrq->nr_switches++; RQ->curr = Next;//switch the current process to the selected process++*switch_count;//Switch Count updateContext_switch (RQ, Prev, next);/*unlocks the RQ*/ //Process Context Switch        /** The context switch has flipped the stack from under US * and restored the local variables which we Re saved when * This task called schedule () in the past.         Prev = = Current * was still correct, but it can be moved to another CPU/RQ. */CPU=smp_processor_id (); RQ=Cpu_rq (CPU); } ElseRaw_spin_unlock_irq (&rq->Lock); Post_schedule (RQ); //notifies the scheduling class to complete the process switchpreempt_enable_no_resched (); if(Need_resched ())//If the process is set by another process with the tif_need_resched flag, the function re-executes the dispatch        Gotoneed_resched;}

6. View of the operating system model the operating system is a computer program that implements resource management, program control, and human interaction. The equipment resources and information resources of the system are assigned and dispatched according to the requirement of the user, and the execution of a user program is carried out under the control of the operating system; The human-computer interaction function of the operating system can make the computer system more "friendly". 7. References

Https://baike.baidu.com/item/%E8%BF%9B%E7%A8%8B/382503?fr=aladdin

52530129

52204016

Http://blog.sina.com.cn/s/blog_9ca3f6e70102wkwq.html

First assignment: Deep source analysis process model based on Linux system

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.