[Linux system] Part 8: Process concept in Linux operating system (von Neumann + operating system + process status + process priority)

1. Von Neumann architecture (hardware)

The von Neumann architecture is the basis of modern computers, and most computers are still organized in the Von Neumann computer structure. (Below is a picture of von Neumann architecture)
insert image description here
Explanation:

  • Memory: Corresponding to the memory in our computer
  • Central processing unit CPU: It consists of two parts: the arithmetic unit and the controller
  • Input devices: including keyboard, hard disk, mouse, etc.
  • Output devices: printers, monitors, etc. (input devices and output devices are collectively referred to as peripherals)
  • Both input and output devices are: disk, network card, etc. Disks can permanently store data

From the above picture, we can draw some conclusions and the process of CPU processing data:
1. Peripherals do not directly interact with CPU, but interact with memory first, and then interact with CPU, because peripherals run The speed is relatively slow, and the computing speed of the CPU is very fast. In order to balance the speed between the two, the CPU will first interact with the memory between the two operating speeds.

2. When reading data, the input device writes the data into the intermediary memory, and then the memory writes the data into the CPU, allowing the CPU to process the data. After processing, the CPU writes the data back into the memory, and finally the Memory writes data out to output device

Summarize:

The CPU does not directly deal with peripherals, but directly deals with memory

For example: the flow of data when you use QQ to chat with friends

To use QQ, you first need to be connected to the Internet. Assuming that the computers of you and your friends are all von Neumann architectures, in the process of sending messages to your friends, the keyboard in your computer acts as the input device, and the monitor and network card act as the output. device, the network card in your friend's computer acts as the input device, and the monitor acts as the output device.
insert image description here

At the beginning, you type a message in the keyboard, and the keyboard loads the message into the memory. At this time, your monitor can get the message from the memory and display it on your own monitor. At this time, you can see your message on your own computer. The message was sent.
After the keyboard loads the message into the memory, the CPU obtains the message from the memory and encapsulates the message in various ways, and then writes it back to the memory. At this time, your network card can obtain the encapsulated message from the memory, and then send it to the network After a series of processing (the details of network processing are ignored here), your friend's network card gets the message you sent from the network, loads the message into the memory, and your friend's CPU gets the message from the memory and processes it. The message is unpacked, and then the unpacked message is written back to the memory, and finally your friend's monitor gets the message from the memory and displays it on his computer.
insert image description here
Note: The same device may be an input device or an input device in different scenarios.

After understanding the above series of theories, we can understand a question: Why must the program be loaded into memory before running?
Because the executable program (file) is on the disk (peripheral), and the CPU can only obtain data from the memory, the data on the disk must be loaded into the memory first, that is, the program must be loaded into the memory first.

Second, the operating system (software)

1. Concept

Simple understanding: The operating system is a software that manages hardware and software resources.

insert image description here

2. The purpose of designing the operating system

  1. For (users, programmers): provide users with a stable, efficient and secure operating environment, and provide programmers with various basic functions (OS does not trust any users, and does not allow users or programmers to interact with hardware)
  2. Next: Manage various hardware and software resources

3. Positioning

In the entire computer hardware and software architecture, the positioning of the operating system is: a pure " management " software

4. How to understand "management"

os complete architecture

First of all, what we can see with the naked eye is the actual computer, that is, the underlying hardware of the computer. These hardwares seem to be listed one by one, but in fact they all follow the von Neumann organizational form at the bottom.
insert image description here

It is not enough to only have these hardware, but also need a software to manage these hardware. For example, when does memory read data from an input device? How much data is read? When does memory flush buffers to output devices? Is it refreshed by row or all refreshed? These are managed by software, and this software is the operating system (Operator System).
insert image description here

At this point there is a question: does the operating system directly deal with the underlying hardware?
For example, if the operating system completes the keyboard reading operation by itself, as long as your keyboard reading method is changed, the kernel source code of the operating system needs to be recompiled, which is too expensive for the operating system to maintain. Taller.
So we added a driver layer between the operating system and the underlying hardware . The main job of the driver layer is to control the underlying hardware alone. For example, a keyboard has a keyboard driver, a network card has a network card driver, a hard disk has a hard disk driver, and a magnetic disk has a disk driver. Simply speaking, the driver is to access a certain hardware, access the reading and writing of the hardware, and the current state of the hardware, etc. The driver layer directly deals with the hardware. The driver is generally provided by the hardware manufacturer, or developed by an operating system-related module (such as a network card). At this point, the operating system only needs to care about when to read the data, not how the data is read, that is, the decoupling between the operating system and the hardware is completed.

insert image description here

What exactly does the operating system manage? The operating system mainly performs the following four management tasks:

  1. Memory management: memory allocation, memory sharing, memory protection, memory expansion, etc.
  2. Driver management: operations such as classifying, updating, and deleting computer device drivers.
  3. File management: file storage space management, directory management, file operation management, file protection, etc.
  4. Process management: Its work is mainly process scheduling.

insert image description here

And the operating system is where we are, where we can use the command line or graphical interface to perform various operations. This layer is called the user layer.
insert image description here

However, in order to protect itself, the operating system only exposes some interfaces and does not allow users to directly access the operating system. This series of interfaces is called a system call interface.
insert image description here

But these system call interfaces are too expensive for our ordinary users, because the prerequisite for using system calls is that you have to have a certain understanding of the system. Therefore, a number of libraries have been built on top of the system call interface, such as libc and libc++. In fact, various libraries used at the language level encapsulate the system call interface, and we write various programs by calling various functions (such as printf and scanf) in these libraries.

insert image description here

Understanding "management"

The essence of management: manage the data Management
method: first describe, then organize.

If you want to learn the operating system well, you must correctly understand what management is.

First distinguish the difference between decision-making and execution

  1. Decision-making: Take the above-mentioned operating system hierarchy as an example, the operating system in it has "decision-making power" and can be a manager.
  2. Execution: In the above operating system hierarchy, the driver executes the tasks issued by the operating system.

Next we give an example to talk about management. For example, school management (roughly summarized).
Three roles are given: student, counselor, principal. Obviously, the principal is the manager among these three people, and the students are the managed. So what role does the counselor play?
insert image description here
Think about it, we have to go through two processes to accomplish one thing, the first is to decide whether or not to do this thing or how to do it (making a decision), and then to execute this thing.

As a manager, the principal can formulate rules for the school to manage the school, so the principal is the one who makes decisions, but after the principal makes a decision, he does not need to implement it himself, but let the counselor implement it, so the main task of the counselor is Execute the decisions of managers, we call them executives
insert image description here

Although it is said that the principal manages the students, we generally cannot see the principal himself in the school, so how can the principal manage us without seeing us?

For example: Now the principal asks the counselor to count the grades and information of the students in various subjects. When the counselor brings the student information, the principal finds a way to select the top three students to give scholarship awards.

During this process, the principal managed these three students without ever seeing them. What was his basis? Yes, he was based on data.

In fact, the school manages all kinds of information about each of our students, including basic information, performance information, and health information.
insert image description here

Each such set of information describes a student, and the principal can manage the students through the management of these information. Such a set of information is called abstract structure in C language, and object-oriented in C++.

When the number of students increases, the principal can organize the information of all the students. Of course, there are many ways of organization (linked list, sequential list, tree), and each organization method has its own advantages, so there is There is a course dedicated to teaching us how to manage data, and that is data structures. Here we assume that the principal organizes the student information in the form of a linked list.
insert image description here

At this time, the principal's management of each student actually becomes the addition, deletion, checking and modification of this linked list. When there is a new student, directly add a node to the linked list, and when the student graduates, just remove the student information from the linked list.

5. Concepts of system calls and library functions

  1. From the perspective of development, the operating system will appear as a whole to the outside world, but it will expose part of its interface for upper-layer development. This part of the interface provided by the operating system is called a system call.
  2. In terms of system calls, the functions are relatively basic, but the requirements for users are relatively high. Therefore, interested developers can properly encapsulate some system calls to form a library. With a library, it is very beneficial to upper-level users. Or developers carry out secondary development, such as cin, cout, etc. that we often use.

3. Process management

1. The concept of process

We can see the following points about the concept of process in books:

A running (loaded into memory) program - - - process
A program in memory - - - process
Compared with programs, processes have dynamic properties

From the above points, we still don't understand the concept of process, and we can't distinguish the difference between program and process.

The essence of the program: it is a file, placed on the disk.

What about the process?
Anyone who has written code knows that when your code is compiled and linked, an executable program will be generated. This executable program is essentially a file that is placed on the disk. When we double-click the executable program to run it, we are essentially loading the program into the memory, because the CPU can execute it only after it is loaded into the memory, and once the program is loaded into the memory, we This program should not be called a program anymore, it should be called a process in the strict sense.
insert image description here

2. Describe the process - - -PCB

A large number of processes can exist in the system at the same time. Use the command ps aux to display the processes existing in the system.
insert image description here

When we turn on the computer, the first program to start is our operating system (that is, the operating system is the first to be loaded into the memory). We all know that the operating system does management work, and it includes process management. There are a large number of processes in the system, so how does the operating system manage the processes?

At this time, we should think of the six-character mantra of management: first describe, then organize. The same is true for the operating system management process. As a manager, the operating system does not need to communicate directly with the managed (process). When a process appears, the operating system immediately describes it, and then manages the process In fact, it is the management of its description information.

  • Process information is placed in a data structure called a process control block , which can be understood as a collection of process attributes
  • It is called PCB (process control block) in the textbook , and the PCB under the Linux operating system is: task_struct.

A type of task_struct-PCB

The process control block (PCB) describes the process. In C++ we call it object-oriented, and in C language we call it structure. Since the Linux operating system is written in C language, the process in Linux A control block must be implemented with a structure.

  • PCB is actually a general term for the process control block, and the structure describing the process in Linux is called task_struct.
  • task_struct is a data structure of the Linux kernel that is loaded into RAM (memory) and contains process information.

task_ struct content classification

task_struct is the process control block in Linux, task_struct mainly contains the following information:

  • Identifier: Describe the unique identifier of this process, which is used to distinguish other processes.
  • Status: Task status, exit code, exit signal, etc.
  • Priority: Priority relative to other processes.
  • Program Counter (pc): The address of the next instruction in the program to be executed.
  • Memory pointers: Including pointers to program code and process-related data, as well as pointers to memory blocks shared with other processes.
  • Context Data: The data in the processor's registers when the process is executing.
  • I/O status information: Including displayed I/O requests, I/O devices allocated to the process and a list of files used by the process.
  • Billing information: May include sum of processor time, sum of clocks used, time limits, billing account number, etc.
  • other information.

Since the process information is placed in a process control block (PCB), the operating system will describe each process to form a process control block (PCB) one by one, and organize these PCBs in the form of a linked list .
insert image description here
In this way, the operating system can access all PCBs as long as it gets the head pointer of this linked list. Since then, the management of each process by the operating system has become a series of operations on this linked list.
insert image description here
For example, to create a process is actually to load the code and data of the process into the memory first, and then the operating system describes the process to form a corresponding PCB, and inserts the PCB into the linked list. Exiting a process actually means first deleting the PCB of the process from the linked list, and then the operating system releases or invalidates the code and data belonging to the process in the memory.

In general, the management of the process by the operating system actually becomes operations such as adding, deleting, checking, and modifying the linked list.

From the above explanation, we can know what the process is composed of:

Process = kernel data structure (task_struct) + disk code and data corresponding to the process

3. View process

View through the system directory

Process information can be viewed by viewing the system directory /proc:
insert image description here
The Linux system provides a way to view files to view processes. At the beginning of each process creation, a directory will be created under the /proc directory and named after the process number. Disappears automatically when the process ends.

View by ps command

View process commands:

ps axj | grep myproc

Can display all process information about myproc.
insert image description here

ps axj | head -1 && ps axj | grep myproc

This command can carry the subtitle of the process.
insert image description here

4. Obtain the process identifier (PID/PPID) through the system call

First understand the functions of the two system calls:
Function: Get the process number
insert image description here

subprocess getpid()

getpid() Gets the process ID of the child process.
We can test it with a piece of code.

#include <stdio.h>    
#include <unistd.h>    
#include <sys/types.h>                              
int main()    
{
    
           
    printf("我是一个进程,我的ID:%d\n",getpid());
    sleep(1);             
    return 0;
}  

insert image description here

parent process getppid()

getpid() Gets the parent process ID of the process.

#include <stdio.h>    
#include <unistd.h>    
#include <sys/types.h>                              
int main()    
{
    
           
    printf("我是一个进程,我的ID:%d,PPID: %d\n",getpid(),getppid());
    sleep(1);             
    return 0;
}  

insert image description here

5. Create a process through a system call - fork initial

The fork function creates a child process

fork is a system call-level function whose function is to create a child process.
insert image description here
First look at the following piece of code:

#include <stdio.h>      
#include <unistd.h>      
   
int main()      
{
    
        
    fork();    
    printf("MyPID=%d,MyPPID=%d,%d\n",getpid(),getppid());                                                                                                               
    return 0;                                 
}  

The result of the code operation is as follows:
insert image description here
the result of the operation is to print two lines of data, we can find that the PPID of the second line is the same as the PID number printed in the first line, that is to say, there is a parent-child relationship between the two processes, and the process below is the child process.

Every time a process appears, the operating system will create a PCB for it, and the process created by the fork function is no exception.

We know that the code and data loaded into memory belong to the parent process, so where does the code and data of the child process created by the fork function come from?

Let's take a look at the running results of the following code:
insert image description here
Running results:
insert image description here
In fact, using the fork function to create a child process, the code before the fork function is called is executed by the parent process, and the code after the fork function, by default, both parent and child processes can implement. It should be noted that although the parent and child processes share code, the data of the parent and child processes each open up space (using copy-on-write).

Tips: After using the fork function to create a child process, there are two processes. The order in which these two processes are scheduled by the operating system is uncertain, which depends on the specific implementation of the operating system scheduling algorithm.

Use if to divert

As mentioned above, the child process created by the fork function shares a code with its parent process, but if we really let the parent and child processes do the same thing, then creating a child process is meaningless.
In fact, after fork, we usually use an if statement to split, that is, let the parent process and the child process do different things.

Before using if for shunting, we need to understand the return value of the fork() function.

The return value of the fork function:
insert image description here

1. If the child process is created successfully, return the PID of the child process in the parent process, and return 0 in the child process.
2. If the child process fails to be created, -1 is returned in the parent process.

Since the return value of the fork function obtained by the parent process and the child process is different, then we can use this to let the parent and child processes execute different codes to do different things.
For example, the following code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
    
        
                                                                    
    pid_t id=fork();                                                
    if(id==0)                                                       
    {
    
                                                                   
        //子进程    
        while(1)    
        {
    
                                                                                                                           
            printf("我是一个子进程,MyPID=%d,MyPPID=%d,%d\n",getpid(),getppid(),id);    
            sleep(1);
        }                                                                      
    }                                                                                                  
    else if(id>0)                                                                                      
    {
    
                                                                                                      
        //父进程                                                                                       
        while(1)                                                                                       
        {
    
                                                                                                  
            printf("我是一个父进程,MyPID=%d,MyPPID=%d,%d\n",getpid(),getppid(),id);      
            sleep(1);
        }                                                                                              
    }                                                                                                  
    else                                                                                               
    {
    
     
    }
    return 0;
}

After fork creates a child process, the child process will enter the loop printing of the if statement, and the parent process will enter the loop printing of the else if statement.
insert image description here

Fourth, the status of the process

Processes are in different queues, representing different states.

The source code of the Linux operating system has the following definition for the process state:

/*
* The task state array is a strange "bitmap" of
* reasons to sleep. Thus "running" is zero, and
* you can test for combinations of others with
* simple bit tests.
*/
static const char * const task_state_array[] = {
    
    
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"t (tracing stop)", /* 8 */
"X (dead)", /* 16 */
"Z (zombie)", /* 32 */
};

The current state of the process is saved in its own process control block (PCB), which is also saved in the task_struct in the Linux operating system.

In the Linux operating system, we can view the status of the process through the ps aux or ps axj command.

1. Running status-R

#include <stdio.h>    
int main()    
{
    
        
    while(1);                           
    return 0;    
}

insert image description here
A process in the running state (running) does not mean that the process must be running. The running state indicates that a process is either running or in the run queue. That is to say, multiple R-state processes can exist at the same time.

Tips: All processes that are in the running state and can be scheduled are placed in the run queue. When the operating system needs to switch the process to run, it directly selects the process to run in the run queue.

A + sign behind the status indicates the foreground process , and no + sign indicates the background process . When the foreground process is executing, the user cannot continue to input instructions unless ctrl+c terminates the program; while the background process is executing, the user can input instructions and ctrl+c cannot kill the process. You can use the command kill -9 PID to kill the process.

2. Light sleep state-S

A process is in a light sleep state (sleeping), which means that the process is waiting for something to be completed. A process in a light sleep state can be woken up at any time, or can be killed (sleep here is sometimes called can be interruptible sleep).

For example execute the following code:

#include <stdio.h>    
int main()    
{
    
        
    int a=0;    
    while(1)    
    {
    
        
        printf("%d\n",a++);               
    }                                  
    return 0;                          
} 

insert image description here
Although the value is always printing, the printf function needs to access the display, most of the time is waiting for the display IO to be ready, and only a small part of the time is executing the printing code. So the code renders sleep.
Those that need to access peripherals generally belong to the sleep state.

A process in a light sleep state can be killed, and we can use the kill command to kill the process.
insert image description here

3. Deep sleep state-D

A process is in a deep sleep state (disk sleep), which means that the process will not be killed, not even the operating system, only the process can be recovered automatically when it wakes up automatically. This state is sometimes called an uninterruptible sleep state (uninterruptible sleep), and a process in this state usually waits for the end of IO.

For example, if a process requests to write to the disk, the process will be in a deep sleep state during the writing to the disk and will not be killed, because the process needs to wait for the reply from the disk (whether the write is successful or not) ) to respond accordingly. (disk hibernation state)

4. Pause state-T

You can enter kill -19 PID to put a process into a suspended state.
insert image description here
T suspended state (stopped): A process can be stopped (T) by sending a SIGSTOP signal to the process. The suspended process can be resumed by sending the SIGCONT signal. (kill -18 PID)
insert image description here
Tips: Use the kill command to list the signal sets supported by the current system.

kill -l

insert image description here

5. Track pause status -t

When we use gdb to debug an executable file, the program runs to a breakpoint, and the program will enter the t tracing pause state (tracing stop): indicating that the process is being traced
insert image description here

6. Death state-X

The death state is just a return state. When the exit information of a process is read, the resources requested by the process will be released immediately, and the process will no longer exist, so you will not see the death state in the task list (dead).

7. Zombie state - Z

When a process is about to exit, at the system level, the resources that the process has applied for are not released immediately, but are temporarily stored for a period of time for the operating system or its parent process to read. If it is read, the relevant data will not be released. If a process is waiting for its exit information to be read, then we call the process in a zombie state (zombie).

First of all, the existence of the zombie state is necessary, because the purpose of the process is to complete a certain task, then when the task is completed, the caller should know the completion of the task, so there must be a zombie state, so that the caller can Know the completion of the task, so as to carry out the corresponding follow-up operation.

So how does the process enter the zombie state?

Simulate the scenario where the child process exits normally and the parent process does not recycle the child process (does not read the return information of the child process) (you can also use kill -9 PID to kill the child process): print the process information in a loop through the following
insert image description here
command

while :; do ps axj | head -1 && ps axj | grep mypro | grep -v grep; sleep 1; done

We can find that the child process has become a zombie state. The one next to it is translated as dead. The process has died but has not been recycled. This is the zombie state.

The exit result of the zombie process will be written in the PCB. When a process exits, its code and data will be released, but its PCB will not be released. If the parent process does not reclaim this resource, it will cause system memory leakage. Then can I manually kill this zombie process to manually release zombie resources? No, because the zombie process is dead and cannot be killed manually.

After the process in state Z is recycled, the process state changes to X dead state (dead): after the parent process reads the return information of the child process, the corpse collection speed is too fast for us to see, and the dead state of the process is immediately replaced by its The parent process recycles.

5. Zombie process

  • Zombies are a special state. When the process exits and the parent process (using the wait() system call, described later) does not read the return code of the child process exit, a zombie (corpse) process will be generated
  • A zombie process will remain in the process table in a terminated state, and will keep waiting for the parent process to read the exit status code.
  • Therefore, as long as the child process exits, the parent process is still running, but the parent process does not read the state of the child process, and the child process enters the Z state

As mentioned earlier, if a process is waiting for its exit information to be read, then we call the process in a zombie state. A process in a zombie state is called a zombie process.

For example, for the following code, the child process created by the fork function will exit after printing information 5 times, while the parent process will always print information. That is to say, the child process exits, the parent process is still running, but the parent process does not read the exit information of the child process, then the child process enters the zombie state at this time.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    
    
	printf("I am running...\n");
	pid_t id = fork();
	if(id == 0)
	{
    
     
		//child
		int count = 5;
		while(count){
    
    
			printf("I am child process。PID:%d, PPID:%d, count:%d\n", getpid(), getppid(), count);
			sleep(1);
			count--;
		}
		printf("child quit...\n");
		exit(1);
	}
	else if(id > 0){
    
     //father
		while(1)
		{
    
    
			printf("I am father process。PID:%d, PPID:%d\n", getpid(), getppid());
			sleep(1);
		}
	}
	else
	{
    
     //fork error}
	return 0;
} 

After running the code, we can use the following monitoring script to detect the information of the process every second.

while :; do ps axj | head -1 && ps axj | grep mytest | grep -v grep; sleep 1; done

insert image description here
The dangers of zombie processes

  1. The exit status of the zombie process must always be maintained, because it needs to tell its parent process the corresponding exit information. But the parent process has not read it, so the child process will always be in a zombie state.
  2. The exit information of the zombie process is stored in task_struct (PCB), and the zombie state does not exit, so the PCB needs to be maintained all the time.
  3. If a parent process creates many child processes but does not recycle them, it will cause waste of resources, because the data structure object itself will occupy memory.
  4. The resources requested by zombie processes cannot be recycled, so the more zombie processes there are, the fewer resources are actually available. In other words, zombie processes will cause memory leaks.

6. Orphan process

Most of the process relationships in Linux are parent-child relationships. If the child process exits first and the parent process does not read the exit information of the child process, then we call the process a zombie process. But if the parent process exits first, then when the child process enters the zombie state in the future, there will be no parent process to process it. At this time, the child process is called an orphan process.
If the exit information of the orphan process is not processed all the time, the orphan process will always occupy resources, which will cause a memory leak. Therefore, when an orphan process occurs, the orphan process will be adopted by the No. 1 init process, and then when the orphan process enters the zombie state, it will be processed and recycled by the int process.

For example, for the following code, the child process created by the fork function will always print information, but the parent process will exit after printing information 5 times, and the child process will become an orphan process at this time.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
    
    

    pid_t id = fork();
    if(id == 0)
    {
    
    
        while(1)
        {
    
            
        	printf("我是一个子进程:pid: %d, ppid: %d\n",getpid(),getppid());
	        sleep(2);
        }   
    }
    else if(id > 0)
    {
    
    
    	int count = 5;
        while(count)
        {
    
     
            printf("我是一个夫进程:pid: %d, ppid: %d\n",getpid(),getppid());       
            sleep(1);
            count--}
        printf("父进程退出.......\n");
        exit(1);
    }
	else{
    
     //fork error
	}
    return 0;
}

Observe the code running results. When the parent process does not exit, the PPID of the child process is the PID of the parent process. After the parent process exits, the PPID of the child process becomes 1, that is, the child process is adopted by process 1.
insert image description here

7. Process priority

1. Basic concepts

What is priority?

Priority is actually the order in which certain resources are obtained, and process priority is actually the order in which processes obtain CPU resource allocation, which refers to the priority of the process. Processes with high priority have priority in execution.

Why do priorities exist?

The main reason for the existence of priority is that resources are limited, and the main reason for the existence of process priority is that CPU resources are limited. A CPU can only run one process at a time, and there can be multiple processes, so there is a need for process priority. Level, to determine the order in which processes obtain CPU resources.

2. Check the system process

In the Linux or Unix operating system, using the ps -l command will output the following content similarly:

ps -l

insert image description here
We can easily notice several important information, as follows:

  • UID : represents the identity of the executor
  • PID : represents the code name of this process
  • PPID : Represents which process this process is derived from, that is, the code name of the parent process
  • PRI : Represents the priority that this process can be executed, the smaller the value, the earlier it will be executed
  • NI : represents the nice value of this process

3, PRI and NI

  • PRI represents the priority of the process. In layman's terms, it is the order in which the processes are executed by the CPU. The smaller the value, the higher the priority of the process.
  • NI stands for the nice value, which represents the modified value of the priority at which the process can be executed.
  • The smaller the PRI value, the faster it will be executed. When the nice value is added, the PRI will become: PRI(new) = PRI(old) + NI.
  • If the NI value is negative, the PRI of the process will be smaller, that is, its priority will be higher.
  • To adjust the process priority, under Linux, is to adjust the nice value of the process.
  • The value range of NI is -20 to 19 , a total of 40 levels.
  • Therefore, the permission range of a process in Linux is [80-20, 80+19], and the smaller the number, the higher the priority.

Note: In the Linux operating system, PRI(old) defaults to 80, that is, PRI = 80 + NI.

4. View process priority information

When we create a process, we can use the ps -al command to view the priority information of the process.

ps -al

insert image description here
Note : In the Linux operating system, the initial process general priority PRI defaults to 80 , and NI defaults to 0 .

5. Change the nice value of the process through the top command

The top command is equivalent to the task manager in the Windows operating system. It can dynamically display the resource usage of the processes in the system in real time.
insert image description here

Press the "r" key after using the top command , you will be asked to enter the PID of the process whose nice value is to be adjusted .

insert image description here

After entering the process PID and pressing Enter, you will be asked to enter the adjusted nice value.
insert image description here

Enter the nice value and press Enter to exit. If the nice value we entered here is 15, then we can use the ps command to view the priority information of the process, and we can find that the NI of the process has changed to 15. PRI becomes 95 (80+NI).
insert image description here
What we modify here is the nice value of the child process.

Note: If you want to adjust the NI value to a negative value, that is, increase the priority of the process, you need to use the sudo command to elevate the privilege.

[wyt@VM-20-4-centos test]$ sudo top

Then the operation is the same as above. When modifying the nice value, fill in a negative number.
insert image description here

6. Change the nice value of the process through the renice command

Use the renice command, followed by the changed nice value and the PID of the process.
insert image description here
We may see here that we are a little confused, why is it 90 at the beginning, when we modify the nice value to -10, the new PRI value is 70 instead of 80? In fact, after modifying the nice value, the calculation starts from the default value of PRI, 80, by default. That's why it's 70.

8. Four important concepts

  • Competitiveness: There are many system processes, but only a small amount of CPU resources, or even one, so the processes are competitive. In order to complete tasks efficiently and compete for related resources more reasonably, there are priorities.

  • Independence: Multi-process operation requires exclusive use of various resources, and does not interfere with each other during multi-process operation.

  • Parallelism: Multiple processes run simultaneously under multiple CPUs, which is called parallelism.

  • Concurrency: Multiple processes use process switching under one CPU to allow multiple processes to advance within a period of time, which is called concurrency.

What is process switching?
There is an eip register (PC pointer) in the cpu, which points to the address of the next instruction.

When a process is running, it occupies the CPU and generates a lot of temporary data, which belongs to the current process. Although there is only one set of register hardware inside the CPU, the data stored in the register belongs to the current process. (Registers are shared, but data is private to each process)

When a process is running, it has its own time slice. Once this time is up, even if the process has not been executed, the CPU will be stripped by the operating system to free up the CPU for the next process to run.

So when this process returns to the CPU to continue running next time, how does the operating system know where the code of this process is executed?

First of all, when the process is switched, context protection is required, and some temporary data is saved to the PCB; when the process is resumed, the context needs to be restored, and when the process returns to the CPU to run, the data will be loaded. Continue to run the next line of code through the PC pointer.

Guess you like

Origin blog.csdn.net/m0_58124165/article/details/129134213