[Linux learning path] Analyzing environment variables to improve system control

insert image description here

1. Process priority

1.1 What is priority?

Priority determines the order of resource allocation, that is, whoever accesses first and who accesses later. Pay attention to the concept of distinguishing between priority and authority. Authority determines whether it can be done, and priority is to decide who comes first on the basis of what has been determined to be done.

1.2 Why is there priority?

Because there may be multiple processes in the system, but there is only one CPU, it is doomed that all processes need to compete for CPU resources. The operating system must ensure that all processes have healthy competition, that is, each process can use CPU resources. . It's like going to the cafeteria to buy food. If everyone goes to grab the food without queuing up, the weak and weak will never be able to get the food. The order of queuing needs to be determined by priority, with higher priority in the front and lower priority in the back. If our process cannot get CPU resources for a long time due to unreasonable priority design (unreasonable scheduling algorithm design), and the code of this process cannot be promoted for a long time, it will cause the problem of starvation of the process, which is seen by users as App freezes.

1.3 Summary

  • The order of CPU resource allocation refers to the priority of the process.

  • Processes with higher priority have the right to execute first. Configuring process priority is very useful for Linux in a multitasking environment, and may improve system performance (Note: Do not modify process priority at will, only the scheduler can help us schedule processes in the fairest way).

  • You can also run the process on a specified CPU. In this way, assigning unimportant processes to a certain CPU can greatly improve the overall performance of the system.

Second, the priority in the Linux system

2.1 View process priority

//process.c
int main()                                                      
{
    
                                                                   
    while(1)                                                    
    {
    
                                                               
        printf("I am a process, PID:%d, PPID:%d\n",getpid(),getppid());    
        sleep(1);                                               
    }                                                           
    return 0;                                                                                                                                                                                 
}
//通过ps -al 指令可以查看进程的优先级
 ps -al | head -1 ; ps -al | grep process

insert image description here

  • 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 execution priority of this process. The smaller the value, the earlier it will be executed. It is a member of the task_struct structure object.

  • NI : represents the nice value of this process, which is the correction data of the process priority.

2.2 PRI and NI

  • PRI is the priority of the process, or in layman's terms, it is the order in which programs are executed by the CPU. The smaller the value, the higher the priority of the process.

  • NI is what we often call the nice value, which represents the modified value of the priority of the process that can be executed.

  • The smaller the PRI value, the faster it will be executed. After adding the nice value, it will make PRI(new) = PRI(old) + nice.

  • When the nice value is negative, the priority value of the program will be smaller, that is, the priority will be higher, and it will be executed by the CPU sooner.

  • So to adjust the process priority, under Linux is to adjust the nice value of the process.

  • The value range of nice value is [-20,19], a total of 40 levels.

2.3 Modify process priority

Ordinary users cannot modify the process priority, so you must switch to the root user to modify the process priority.

top
//进入top后按“r”->输入进程PID->输入nice值

insert image description here

Small Tips : PRI(new) = PRI(old) + PRI(old) in nice always starts from 80.

2.4 Implementation Principle of Process Priority

insert image description here
Modifying the priority of a process is essentially modifying the queue where the PCB object of the process is located, and linking the PCB object of the process to the subscript of the array corresponding to the modified priority. Different subscripts correspond to different priority queues.

2.5 Explanation of some terms

  • 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 efficiently complete tasks and compete for related resources more reasonably, they have 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.

In the case of concurrency, the operating system will switch processes according to the time slice of each process. The process currently being scheduled by the CPU will be removed from the CPU by the operating system before its time slice ends, as shown in the above figure In the waiting array in the queue, continue queuing and wait for the next CPU scheduling. We call this process a scheduling algorithm based on time slice rotation. How does the CPU continue to execute from there when it schedules the process next time? The answer is through the program counter (also called the PC pointer), which is a register in the CPU, usually epi, which is used to store the memory address of the next instruction to be executed, so that the CPU will know when it schedules the process next time. From where to continue execution.

Small Tips : There are many kinds of registers in the CPU, for example: general-purpose registers eax, ebx, ecx, edx; ebp, esp, eip related to stack frames; status related to status. Registers also have the ability to save data. When the computer is running, some important data must be stored inside the CPU, that is, in registers. Because the registers are very close to the CPU and have high storage efficiency, the registers in the CPU store process-related data. Can be accessed or modified by the CPU at any time, this kind of data related to the process is also called the context of the process. When a process leaves the CPU. You should save your own context data well, or even take it away. The purpose of saving it is for future recovery. When a process is switched, it needs to perform two steps, that is, save the context and restore the context. The amount of data in the context of the process is not large, and generally can be directly saved to the PCB object of the process. When the CPU schedules the process again, Just restore these context data to the register.

3. Environment variables

3.1 Basic concepts

  • Environment variables generally refer to some parameters used in the operating system to specify the operating environment of the operating system.

  • For example: when we write C/C++ code, when we link, we never know where the dynamic and static libraries we link are, but we can still link successfully and generate executable programs, because there are related environment variables to help the compiler to find.

  • Environment variables usually have some special purpose, and they usually have global characteristics in the system.

insert image description here
The picture above shows the environment variables under the Windows system, which is essentially a set of key-values. Next, some phenomena in Linux will be used to demonstrate common environment variables.

3.2 PATH: command search path in Linux system

We usually need to add ./ when executing the executable program written by ourselves in the bash command line, indicating the executable program in the current directory, telling the operating system to search in this directory when executing, the command is essentially an executable program, but We never add any path when executing the command, so how does the operating system know which directory the command is in? As we mentioned before, all instructions are in /usr/bin/the directory, and the executable program we wrote is in our own current working directory. How can there be a difference if they are all directories? Because the Linux operating system will provide us with an environment variable PATH, which is the command search path provided by the Linux operating system. This environment variable has existed since we booted up and logged in to Xshell. You can view the PATH variable through the following command value.

echo $PATH

insert image description here
The value of the PATH variable is some paths separated by colons. These paths are the paths where the system searches for instructions when we usually execute instructions. This is why there is no need to add ./ when executing instructions, because the system will automatically go to the path corresponding to PATH. Go down the path and search one by one. These instructions are all in /usr/bin/the directory, and /usr/bin/the directory is also the variable value of PATH, so the instructions will eventually be found, and the executable programs we write are generally in the current working directory. This directory is not If you do not add ./ to the value of the PATH variable, the operating system will automatically search all the paths corresponding to the PATH one by one, and finally cannot find the executable program, so it cannot be executed. The current working directory can be added to the environment variable by the following command.

PATH=$PATH:/home/wcy/linux-s/lesson13
///home/wcy/linux-s/lesson13是当前工作目录
//只用=是覆盖写的意思,会把原本的PATH 覆盖掉

insert image description here
Check the value of PATH again, and our current working directory is also added at this time. At this time, the executable program in this directory can be executed without adding ./.

Small Tips : The environment variable we modified above is a memory-level environment variable, which is stored in the shell. Every time you log in to the shell, the environment variable will be loaded from some configuration files of the system to the shell, so our above modification does not It will affect the configuration file of the system, so every time you restart and log in, the environment variables can be restored to the original state.

3.3 HOME

Every time we log in to the shell, we are in the home directory by default. This is because every time we log in, the shell will recognize the currently logged in user and automatically fill in the $HOME environment variable for us. When logging in, the shell will assign a command line for us. The interpreter bash, bash is essentially an executable program, it will help us execute the cd $HOME command, which is why we default to the home directory every time we log in.

Small Tips : We can use the env command to view all the environment variables that the current bash inherits from the operating system.

insert image description here
In addition to using the env command, we can also get the value of an environment variable through the getenv system call interface.

3.4 USER

Authorization authentication can be realized through the USER environment variable. When different users log in to the shell, their USER is their own user name.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    
    
    printf("USER:%s\n",getenv("USER"));
    return 0;
}

Different users of the same code will get different results when they execute it.

insert image description here

#include <stdio.h>
#include <stdlib.h>
int main()    
{
    
        
    char user[32];    
    strcpy(user, getenv("USER"));    
    if(strcmp("root",user) == 0)    
    {
    
        
        printf("root用户,不受权限约束\n");    
    }    
    else    
    {
    
        
        printf("普通用户,受权限约束\n");    
    }    
    printf("USER:%s\n",getenv("USER"));    
    return 0;                                                                         
}    

insert image description here
Formally because of the existence of the USER environment variable, the operating system has the ability to identify the currently logged-in user, and then can compare it with the corresponding owner, group, and corresponding permissions of the file to determine whether the current user has a certain permission.

Fourth, the command line parameters

The main function of C/C++ can pass parameters. These two parameters are called command line parameters, as follows:

int main(int argc, char* argv[])
{
    
    
	return 0;
}

argv is an array of pointers, which stores string addresses, and this array has argc elements.

int main(int argc, char* argv[])    
{
    
        
    int i = 0;    
    for(; i < argc; i++)    
    {
    
        
        printf("argv[%d]->%s\n",i, argv[i]);    
    }    
    
    return 0;                                                                                                                                          
} 

insert image description here
The main function can also be called as a function, and it also has parameters, which can be passed when calling the main function. What we enter on the bash command line: ./mycode -a -b -cwill be regarded as a string by bash, and it will divide the entire string into separate strings with spaces as separators, and then store their addresses in the argv array.

Small Tips : Assuming argc == Nthat there are N command line parameters, then argv[N]will be set to by default NULL.

4.1 The role of command line parameters

#include <stdio.h>

int main(int argc, char* argv[])    
{
    
        
    if(argc != 2)    
    {
    
        
        printf("./mycode [-a|-b|-c|-d]\n");    
        return 0;    
    }    
    
    if(strcmp(argv[1], "-a") == 0)    
    {
    
        
        printf("执行功能1\n");    
    }    
    else if(strcmp(argv[1], "-b") == 0)    
    {
    
        
        printf("执行功能2\n");    
    }    
    else if(strcmp(argv[1], "-c") == 0)    
    {
    
        
        printf("执行功能3\n");    
    }    
    else if(strcmp(argv[1], "-d") == 0)    
    {
    
        
        printf("执行功能4\n");    
    }                                                                                                                                                  
    else     
    {
    
        
        printf("没有该选项!\n");    
    }    
        
    return 0;    
}    

insert image description here
Command line parameters have an important role, it can provide support for command line options for commands, tools, software, etc.

4.2 The third parameter of the main function

In addition to the two parameters argc and argv mentioned above, the main function also has a third parameter env, which is also an array of pointers, storing the environment variables of the process.

#include <stdio.h>
int main(int argc, char* argv[], char* env[])    
  {
    
        
      int i = 0;    
      for(;env[i]; i++)    
      {
    
        
          printf("env[%d]->%s\n", i, env[i]);    
      }    
      
      return 0;                                                                                                                                        
  } 

insert image description here
Summary : The C/C++ code we usually write will have two core vector tables, one is called the command line parameter table, and the other is called the environment variable table. The commands we usually execute and the executable programs we write are all child processes of bash. When bash itself starts, it will read the environment variable information from the configuration file of the operating system, and the child process will inherit the parent process. environment variables. This is the nature of the global nature of environment variables.

4.3 Inheritable verification of environment variables

Use the following command to add our own environment variable in the context data of bash, and verify that the environment variable can be inherited by the child process by checking whether the environment variable exists in the child process.

export MY_VALUE=12345678

insert image description here
Execute the child process below ./mycode, and you can find that it also has the environment variable MY_VALUE, indicating that the child process mycode inherits the environment variable of the parent process bash.

insert image description here
It is precisely because the child process can inherit the environment variables of the parent process, so all the commands we enter in bash must obey the authority, because all the commands entered can be regarded as the child process of bash, and all inherit the environment variables of bash. The environment variable can be deleted by the following command.

unset MY_VALUE

5. Local variables and built-in commands

Local variables are variables defined directly on the command line.

insert image description here
setAll environment variables and local variables in the system can be found through the command. Among them, local variables will not be inherited by child processes, and will only be valid in this bash. A local variable can exportbe turned into an environment variable by the directive.

export MYVALUE
//MYVALUE本来是一个本地变量
//执行完这条指令后MYVALUE就会变成一个环境变量

5.1 Instructions entered on the bash command line do not necessarily create subprocesses

As shown in the figure above, we can echoprint out local variables through the instruction. As mentioned earlier, echoas an instruction, it is essentially an executable program. Since it is an executable program, a process will be created, but we also said that child processes cannot be inherited. The local variables of the parent process, so why can echo print out the local variables of the parent process bash? The reason is: not all instructions create child processes. Instructions can be divided into the following two categories:

  • Regular commands : done by creating subprocesses.

  • Built-in command : bash does not create a subprocess, but executes it by itself, similar to bash calling a function written by itself or provided by the system.

And echo is a built-in command, and no child process will be created when the echo command is executed. Similar to this, there is the cd command, which is also a built-in command, and the working directory of the current process can be changed by calling the chdir system interface.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>                                                                            
   
int main(int argc, char* argv[], char* env[])    
{
    
        
    sleep(30);    
    printf("change begin\n");    
    if(argc == 2)    
    {
    
        
        chdir(argv[1]);    
    }    
    
    printf("change end\n");    
    sleep(30);    
    return 0;    
}   

insert image description here
When the cd command is entered on the bash command line, bash will not create a child process, but will determine whether the command line parameter is cd, and if so, directly call the chdir system interface to switch the working directory.

Small Tips : In addition to the two methods mentioned above to obtain environment variables through code (the third parameter of the command line, getenv system interface), it can also be obtained through the third-party variable environ. The global variable environ defined in libc points to the environment variable table, environ is not included in any header file, so it must be declared with extern when using it.

#include <stdio.h>
int main(int argc, char *argv[])
{
    
    
	extern char **environ;
	int i = 0;
	for(; environ[i]; i++)
	{
    
    
		printf("%s\n", environ[i]);
	}
	return 0;
}

6. Conclusion

Today's sharing is over here! If you think the article is not bad, you can support it three times . There are many interesting articles on Chunren's homepage . Friends are welcome to comment. Your support is the driving force for Chunren to move forward!

insert image description here

Guess you like

Origin blog.csdn.net/weixin_63115236/article/details/132312318