[Introduction to Linux]---Process status

1. Main status of the process

Insert image description here

Process running status

Insert image description here
① There is a run queue in the memory, which has two pointers, one pointing to the PCB address of the head process that has been prepared and linked with a double linked list, waiting to be scheduled to run, and the other points to the tail process, so that it can be well managed. These are the processes waiting to be run;
② There is a scheduler in the run queue. The scheduler calculates the process time slice (the time the process is run) and selects processes to run on the CPU, so that all processes are scheduled as fairly as possible. ;
③ When a process puts itself on the CPU to run, does it have to be executed before it can be put down? Answer: Of course not! For example, if you write while(1)a statement in C language, and you see the statement being executed in the black box on the display screen, remember not to use your perception to guess the running speed of the CPU; in fact, each process runs for a certain amount of time on the CPU. time (maybe about 10ms), it will be put back into the memory's run queue and continue to wait until it is run again. Because the CPU runs too fast, you may not feel it, so you mistakenly think that the process code you wrote has been being processed. Run; when your while(1)statement is running, you can also use process applications such as browsers and QQ. This also shows that the processes take turns running on the CPU!
Summarize:

Processes waiting in the run queue of the memory and processes running on the CPU can be said to be running !

process blocking state

Insert image description here

① Our operating system will describe the attribute information of various peripherals using PCB structures and organize them for management. In the PCB structure describing the peripherals, there are head and tail pointers pointing to the waiting queue. For those who need to wait for peripheral input Process management!
② For example: We use scanf\cinstatements. When this code process is running, it cannot be directly placed in the running queue because it is not ready yet. Before keyboard input, it will be placed in the waiting queue. After input, the process will be placed in the run queue.
③The process is in a state of waiting for peripherals to complete information interaction (information input, output, etc.), which is called the blocking state of the process .

The suspended state of the process

If many processes are in a blocked state, the memory resources of the operating system will be seriously insufficient, and the code and data in the blocked state will be idle. To ensure that the operating system can run normally, the corresponding code and data of the PCB process will be placed in On the disk, the PCB structure only needs to be queued in the waiting queue. When the peripheral inputs information, the code and data in the disk are recalled and recalled into the memory; the space replaced by the operating system can be stored. Other PCB structures improve memory space utilization! (To submit a resume to the interviewer, you only need to wait for your resume to be screened, and you do not need to be present personally)
The PCB in the process is queued in the waiting queue, and resources such as code and data are stored in the disk. This state is called the process of hanging. Starting state
Insert image description here

The above are the three main states of operating system processes: running, blocked, and suspended. Other process states will be learned later.

2.Linux process status

Linux process kernel source code

A process can have several states (in the Linux kernel, processes are sometimes called tasks). The following states are defined in the kernel source code:

/*
* 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 */
};

R运行状态(running): does not mean that the process must be running, it indicates that the process is either running or in the run queue.
S睡眠状态(sleeping): It means that the process is waiting for the event to complete (sleep here is sometimes called interruptible sleep) and
D磁盘休眠状态(Disk sleep)is sometimes called uninterruptible sleep state (uninterruptible sleep). The process in this state usually waits IOfor the end.
T停止状态(stopped): The process can be stopped ( ) by sending the SIGSTOP signal to the process T. The suspended process can SIGCONTcontinue running by sending a signal.
X死亡状态(dead): This status is just a return status, you will not see this status in the task list. Process status view
Z僵尸状态(zombie): The process is not recycled immediately after the process ends, and the process information is maintained.

①R running status

We create a mypro.cfile and write the following code:

#include<stdio.h>    
#include<unistd.h>    
int main()    
{
    
        
    while(1)    
    {
    
        
       printf("hello prosserstate\n");    
    }    
    return 0;                                                                                               
}   

The result of running the code is:
Insert image description here
Monitor with the following command in another window

$ ps ajx | head -1 && ps ajx | grep myproc |grep -v grep

The test results are:
Insert image description here

./myprocThe file has been printing on the display screen, but the monitoring results show that ./myprocthe process is in a sleep state. This is because the CPU is running too fast, and the data to be printed is output to the memory at once, and then slowly output from the memory to the display screen. , most of the time waiting for the display (peripheral) to be ready, so the process has been sleeping.

Let’s slightly modify the above code and then monitor it:

#include<stdio.h>    
#include<unistd.h>    
int main()    
{
    
        
    while(1)    
    {
    
        
       // printf("hello prosserstate\n");    
    }    
    return 0;                                                                                               
}   

The monitoring results are:
Insert image description here

We commented out printfthe statement this time. The CPU no longer needs to interact with the display screen. It only needs to run ./myprocthe process. Therefore, ./myprocthe process is running and in the running state waiting for the run queue, so ./myprocthe process can be monitored R状态.

The difference between whether there is a + sign after the status
① There is a + sign after the status, if the status of a process is R+, it means that the process is running in the foreground; there is no + sign behind the status, if the status of a process is R, it means the process is running in the background; in the background The running process ctrl+Ccannot be terminated. You need to use the kill command to kill the process; add it after the running process &and the process will run in the background.
Insert image description here

②S sleep state

Modify myproc.cthe file code to:

#include<stdio.h>    
#include<unistd.h>    
int main()    
{
    
        
    int a=0;    
    printf("Enter# ");    
    scanf("%d",&a);    
    printf("echo>%d\n",a);    
    while(1)    
    {
    
        
        sleep(1);                                                                
       //printf("hello prosserstate\n");                         
    }                                                            
    return 0;                                                    
}      

When the keyboard is ready to input:
Insert image description here
Enter the following command in another window:

while :;do ps ajx | head -1;ps ajx |grep myproc |grep -v grep;sleep 1;done

The results of monitoring before keyboard input are:
Insert image description here
Numbers input on keyboard:
Insert image description here
The results of monitoring after keyboard input are:
Insert image description here

① To run the above code, data needs to be input from the keyboard. The process is in (sleep state) ./myprocwhile waiting for keyboard input ; ② If the functions in the library are used in the loop , the process will also be in the S state sleep state; ③ We are in xshell Enter the command on the machine, and the bash command line is waiting for us to enter the command, which is in the (sleeping state)S状态whilesleepS状态
Insert image description here

Use topinstructions to monitor the status of each process on the machine:
Insert image description here

It can be seen that most of the process states are in S状态(sleep state), and on Linux systems S状态(sleep state) is the blocking state of the operating system.

③D disk hibernation state

short story:In the operating system, many processes are run every day. One day, a process wants to write 1GB of data to the disk, because the amount of data is too large and the speed of writing from memory to disk is too slow. , so the process can only wait idlely for the success or failure of writing data to the disk, and wait for the disk to feedback information to the process. At this time, the operating system space resources are seriously insufficient, and the blocked process also puts code and data on the disk. The system was in a suspended state, but it was still a drop in the bucket; so the operating system began to observe all processes in the operating system. What was it doing? Of course, we are ready to kill the process! Unfortunately, I found a process that did nothing. Seeing how the operating system could tolerate it, of course the process was killed! The process is the process waiting for 1GB of data to be written to the disk. When the disk writing fails, the disk rushes back and wants to tell the process: "Process, I'm sorry, the writing failed!" but finds that the process is missing. , I had no choice but to continue busy with the work at hand, and the lost data was the user's most important data! As a result, the user angrily took the operating system, process, and disk to court, and all three will receive a fair trial! In court, the judge asked the operating system: "You can punish the operating system, so why do you want to kill the process?" The operating system said confidently: "The law (rules) gives me the power to manage the underlying software and hardware resources and provide users with A good experience, and this process has done nothing. Either I kill him, or the user interface will freeze and crash!" The judge turned to the process and asked: "Process, do you know your guilt?" Process said tremblingly: " Your Honor, I am the victim, and I am unjustly accused! I was waiting for feedback after the disk was written, and then reported the feedback information to the user, and was suddenly killed. It was so difficult for me!" Immediately afterwards The judge asked Disk: "Disk, do you know your guilt?" Disk cried and said: "Your honor, I work around the clock and don't dare to slack off at all. But writing data is slow, so you can't blame me. Writing The data failed, but there is not enough space. I can't just lose the other data and continue writing, right? I'm just a part-time worker, and I just want to work well, woo woo woo!" The judge frowned and thought: "The three of them There seems to be no error, but how can I communicate with the user?" The judge came up with a plan: "You can set a state. While the process is waiting for the disk to write data, the process cannot be killed. This state is for today. In this situation, let’s call this state a disk hibernation state!” The judge promised the user: “I have issued a decree. This situation will never happen again in the future! "Some time after the trial ended, the operating system resources were seriously insufficient. I happened to see a process waiting for a large amount of data to be written to the disk. I should have "raised the knife" to kill the process, but the process calmly took out "free" "Dead gold medal" (that is, telling the operating system that I am in disk hibernation), the operating system has to give up and go to other processes!

The response state after waiting for the end of disk input and output data is D state (disk hibernation state). The operating system cannot host too many processes in D state (generally only one or two are allowed), because too many processes in D state will cause The system cannot operate normally (it is too stuck); the status switching at the operating system level is very fast. If a certain process can be found to be in D state by the user, it means that the operating system has been stuck for a long time!

T stop state

Use the following code file:

#include<stdio.h>    
#include<unistd.h>    
int main()    
{
    
        
   while(1)    
   {
    
        
       sleep(1);    
       printf("hello prosserstate\n");    
   }    
   return 0;                                                                                                                                                         
}  

The kill command controls process suspension:
Insert image description here
command understanding:

kill -9 Pid //杀进程
kill -19 Pid//暂停进程
kill -18 Pid//重新启动进程

The state of the process before suspending it:

Insert image description here
Insert image description here
The state of the process after suspending the process:
Insert image description here
Insert image description here
The state of the process after restarting:
Insert image description here

Use the kill related command to pause the process. After the process is paused and restarted, you can find that the process is running in the background. The process cannot be terminated by pressing ctrl+C. You need to use the kill command to terminate the process.

GDB debugging to observe T status:
Insert image description here
Enter the following command in another window:

ps ajx | grep myproc

The monitoring results are:
Insert image description here

① We usually interrupt the debugging code. Letting the code run to the endpoint is the result of pausing the code process. Therefore, the process is in a paused state to better control the process; ② It is temporarily considered that the t state and the T state are consistent. , that is, they are all in a suspended state!

The difference between process S state and T state:

It seems that the processes in the two states are not running on the CPU, but the purposes of the processes in the two states may be different. The process in the S state is to wait for a certain resource (such as keyboard input), while the process in the T state is waiting for a certain resource (such as keyboard input). The process may also be waiting for a certain resource to be ready, or it may be to control the process to achieve a certain purpose (for example, you just don't want the process to run).

④X death state

We call the process exit, and the state in which the process resources have been recycled is called the X state (death state).

⑤Z zombie state

In the operating system, some processes exit normally after completing the task, or exit due to accidental process termination. Regardless of the above situation, as long as the process exits, it will be placed in the garbage queue, waiting for resource recycling, and the exiting process information resources It will last for a period of time, and the process state at this time is called the Z state (zombie state). The information resources of the process will not be recycled by the system until the parent process "cares" about the process (receives the exit information of the process).

#include<stdio.h>    
#include<unistd.h>    
int main()    
{
    
        
    pid_t id=fork();    
    if(id==0)    
    {
    
        
        int cnt=5;    
        while(cnt--)    
        {
    
        
            printf("i am child, pid: %d ppid:%d\n",getpid(),getppid());    
            sleep(1);    
        }    
       // exit(0);    
    }    
    else if(id>0)    
    {
    
        
        while(1)    
        {
    
        
            printf("i am father, pid: %d ppid:%d\n",getpid(),getppid());         
            sleep(1);                                    
        }  
        //父进程当前没有针对子进程做任何事情                                                       
    }                  
    return 0;    
}                                                                         
    

The running and monitoring results of the code run are:
Insert image description hereInsert image description here

forkA child process is created using a process. After 5 seconds, the child process ends normally and is not recycled by the parent process that created it. The word also means defunctzombie, indicating that the process will be in a zombie state; ② When a process generally exits, if If the parent process does not actively recycle, the child process will always keep itself in the Z state, and the resources of the process, especially the task_struct structure, cannot be released.

Dangers of zombie processes:

  • The exit status of the process must be maintained, because it needs to tell the process that cares about it (the parent process) how well I did the task you gave me. But if the parent process never reads, then the child process will always be in Z state? Yes!
  • Maintaining the exit status itself requires data maintenance, and it is also the basic information of the process, so it is stored in task_struct (PCB). In other words, the Z state will never exit, and the PCB will always need to be maintained? Yes!
  • Which parent process creates many child processes but does not recycle them? Will this cause a waste of memory resources? Yes! Because the data structure object itself takes up memory, think about defining a structure variable (object) in C to open up space at a location in the memory, which will cause a memory leak in the operating system!

⑥Orphan process

  #include<stdio.h>          
  #include<unistd.h>                        
  int main()               
  {
    
        
      pid_t id=fork();                                                 
      if(id==0)                                                      
      {
    
                                                           
          while(1)                        
          {
    
                                                     
         	printf("i am child procsser,pid: %d ppid: %d\n",getpid(),getppid());    
              sleep(1);    
          }    
      }    
      else if(id>0)    
      {
    
        
          int cnt=5;    
          while(cnt--)    
          {
    
        
              printf("i am father procsser,pid: %d ppid: %d %d\n",getpid(),getppid(),cnt);    
              sleep(1);    
          }    
              
      }                                                                                                   
      return 0;    
  }                                      

The running and monitoring results of the code running are:
Insert image description here
Insert image description here
View the process with Pid 1
Insert image description here

Use the fork function to create a child process. The parent process exits first. The parent process of the child process will be changed to process No. 1 (operating system), which means that the process is adopted by the parent process and becomes an orphan process.

  • Question: If the parent process exits early and the child process exits later and enters Z, what should be done?

The parent process exits first, and the child process is called an "orphan process". The orphan process is adopted by init process No. 1. Of course, there must be an init process to recycle it.

3. Summary

There are three main states at the operating system level: running state, blocked state, and suspended state; in Linuxthe operating system, R状态it can correspond to the running state on the operating system, S\D\Tand the state corresponds to the blocked or suspended state on the operating system, X/Zand so on. The state corresponding to the operating system may be implemented (divided) differently between operating systems, but the principles (concepts) of the state are similar.
Insert image description here

Guess you like

Origin blog.csdn.net/m0_74288306/article/details/132620956