Linux process Environment

Source: Internet
Author: User
Tags cpu usage

1. What is the process?

The running program is the process, the process is dynamic, the program is static, and the process has a state change during execution.

The process has three different states: running, ready, blocking;

Three-model analysis:

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M00/87/3F/wKiom1fYydLw1noWAAAY_p-_hw8097.png-wh_500x0-wm_3 -wmp_4-s_2710365820.png "title=" Qq20160914115333.png "alt=" Wkiom1fyydlw1nowaaay_p-_hw8097.png-wh_50 "/>

View process commands Ps-ef and top, kill PID (Kill process)

Run state: The process obtains CPU resources, can use the instructions in the CPU computer program, when the CPU usage time runs out, then enters the ready state.

Ready state: Other resources are ready, only CPU resources.

Blocking states: processing other resources other than the CPU is not yet ready.

Process scheduling: The process starts in a ready state, in order to schedule the process of CPU use, given the process priority, the modern operating system priority is a number of major parameters dynamic change.


2. Process Management block

A PCB is a collection of information that the operating system abstracts out to facilitate the management of all processes.

Main information of PCB preservation:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/87/42/wKiom1fY-0DzhzZCAABYi9Mh1bo147.png-wh_500x0-wm_3 -wmp_4-s_1977168056.png "title=" Qq20160914122006.png "alt=" Wkiom1fy-0dzhzzcaabyi9mh1bo147.png-wh_50 "/>


3, the relationship between Linux processes

Linux, the entire operating system to facilitate the management of all processes, so that all the processes are organized together to form a process tree with a subordinate relationship, then under the process tree, in addition to the root process, other processes have a parent process .

That is, the process management blocks of all processes are organized into a large tree-like storage, and any process management block information is a node of this number.

You can view the process tree of the current system using the Pstree command:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/87/3D/wKioL1fY0hfxn839AAC1J8Y8Y9g510.png-wh_500x0-wm_3 -wmp_4-s_89145685.png "title=" Qq20160914122852.png "alt=" Wkiol1fy0hfxn839aac1j8y8y9g510.png-wh_50 "/>

4. Create a process

The creation of a process is done by 2 system function families.

(1), Execv function family

int execl (const char *path, const char *arg, ...); int EXECLP (const char *file, const char *arg, ...); int execle (const char *path, const char *arg, ..., char * const envp[]); int execv (const char *path, Char                   *const argv[]); int EXECVP (const char *file, char *const argv[]); int execvpe (const char *file, char *const argv[], Char *const envp[]);

(2), fork function family

pid_t fork (void);


5. Execv function

EXECV function: loads a file on the file system into memory and executes it .

int execv (const char *path, char *const argv[]); Path to the executable file, NULL

Cases:

#include <stdio.h>
#include <unistd.h>

int main (void) {
printf ("This is EXECV testing \ n");
Execv ("./test3", NULL); Test3 is an executable file that executes the Test3 file in turn, and the original process will no longer execute after the statement.
printf ("Meeting execv after\n"); This statement is not executed because after the EXECV function.

return 0;
}

Run results

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/87/40/wKiom1fY2dOA7tlmAABWkTGIK7Q535.png-wh_500x0-wm_3 -wmp_4-s_871530519.png "title=" Qq20160914130157.png "alt=" Wkiom1fy2doa7tlmaabwktgik7q535.png-wh_50 "/>

(1), when the EXECV function runs a file, the original process is replaced, the process of executing the file, the original process will no longer execute the subsequent statement.

(2), the main role of the EXECV function: the external memory (file system) in the process of loading an executable file into memory, will be refreshed call execv function of the current process of the PCB, the majority of content is rebuilt, leaving a small portion of content (process ID, process relationship).

(3), the EXECV function does not allow the number of processes in the system to increase.


6. Fork function

Fork function: The process that calls the fork function will copy a child process based on the contents of the current process, then the current process becomes the parent of the new process, and the content of the new process is almost identical to the content of the parent process.

Fork is the technique of the process.

The child process will get a copy of the exact process content (data segment, code snippet, stack segment, register state, most of the content in the PCB) according to the parent process, but some content is still different (process ID, process relationship).

The understanding of the PID = fork () statement:

(1), fork () function----------> Create process

(2), the return value has 2, will share all subsequent code; The value of the PID of the subprocess: Success or failure of the tag, 0 success, not 0 failures;

PID value of the parent process: is the PID number of the child process.

(3), child process/parent process who runs first, fair competition, not necessarily.

(4), creation failure, the value of the PID of the child process:-1; The value of the parent process PID: The number of the cause of the error.

(5), be sure to see who is the current process? Child process/parent process.

(6), there are two methods to get the process PID, Getpid () and Getppid (); Get the PID of the current process and the current parent process;

At this point it is possible to get the following statement:

PID = fork ();   2 process fork (); 4 processes

The above statement will produce 4 processes, the creation process is successful, the total number of processes is 2^n, because the process is highly independent and closed, so the data between is not shared.

The resulting process model is as follows:

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M00/87/40/wKioL1fZArKyaxiNAABXbY7T9HA875.png-wh_500x0-wm_3 -wmp_4-s_697088918.png "title=" Qq20160914155621.png "alt=" Wkiol1fzarkyaxinaabxby7t9ha875.png-wh_50 "/>


A simple process to create:

#include <stdio.h> #include <unistd.h>int main (void) {pid_t pid;    PID = fork ();    if (PID > 0) {printf ("This is father\n");    }else if (pid = = 0) {printf ("This is child\n");            }else{perror ("");    return-1; } return 0;}

Run results

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M00/87/49/wKiom1fadhWxuPmTAAAqLvu2i_s089.png-wh_500x0-wm_3 -wmp_4-s_376684497.png "title=" Qq20160915182056.png "alt=" Wkiom1fadhwxupmtaaaqlvu2i_s089.png-wh_50 "/>


The parent process ends before the child process, but all processes execute, and the program ends when all the processes are executed.

Model analysis

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/87/49/wKiom1fabBzB0o7fAACF6ZT_kHE452.png-wh_500x0-wm_3 -wmp_4-s_248260202.png "title=" Qq20160915173819.png "alt=" Wkiom1fabbzb0o7faacf6zt_khe452.png-wh_50 "/>

Although a child process is a full copy of the parent process, it is possible to determine the difference in the return value of the fork, to the extent that the child process and the parent process perform exactly the same content.

The sub-processes that the fork gets are the same as the parent process content, but the process is highly independent, so the data between them is not shared (the overall logical view).

Each process can carry out internal memory operations are on the basis of virtual memory, a process in the absence of special means, it can only see itself, and not see the existence of other processes, the process is "arrogant", because of the existence of virtual memory, the process thought that the memory size that it can access is 2 address bus several Times Square ( The entire computer's memory is the process).


7. Diversity of processes

Knowing Execv and fork, there is no way to directly meet the diverse task requirements of the operating system using execv/fork alone.

The EXECV and fork must be used together at this point.

pid_t pid = fork (), if (PID = = 0) {execv ("", NULL); The child process executes the executable file specified by EXECV, executes other processes, and then the statements are replaced. }else if (pid > 0) {//parent process executes this process. }elses{perror ("");}

The multi-process diversity of the system is achieved through the replacement of the clone.

From this point of view, (1), fork the task is to create a new process, (2), the responsibility of the EXECV function is to replace (implement a new process to perform different content---from the binary executable content).

Linux system startup Why is it a tree structure?

During the Linux boot process, only the first initiated process (the INIT/SYSTEMD process) is not fork-generated, and the other processes are created by using fork and EXECV, thus enabling a complete process tree to be built.


8. Copy on Write

Is there a problem with the diversity of processes that can be achieved through fork and execv?

If the current process occupies a large amount of content, then by fork to produce a child process will be a huge waste; fork gets a child process as large as the current process, but if the child process is ungrateful (it does not need the legacy of the parent process), instead of EXECV, the content of the entire child process will be modified refreshed , all the content copied from the parent process is invalid.

For the alignment to be optimized effectively, the fork is adjusted.

(1), when the call fork generated sub-process, the most important thing is to create a PCB, you can copy the PCB to copy;

(2), the resulting child process PCB, and assigned a physical address, and will not immediately copy the contents of the parent process to the child process;

(3) Instead, a code snippet that points to a reference (the content of the child process's code snippet points directly to the parent process, and the contents of the child process's data segment are at the beginning also point to the data segment content of the parent process, as well as the heap segment);

(4), copy on write technology: If a child process or parent process is modifying the contents of a data segment or heap segment, the memory of the part that is being modified is copied to the child process immediately before it can be modified. Thus, the independence and closeness of the process are ensured logically.

After the 4 steps above, the fork does not consume too much CPU and memory resources after it is completed. The key to the implementation of this technique is the management of the mapping between the virtual address of the process and the physical address of the computer.

At this time, it would not be a huge waste to call Execv when calling fork.


9, a program caused by the problem:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h>int main (void    ) {pid_t pid;    int i;        for (i = 0; i < 5; i++) {pid = fork ();        if (PID = = 0) {printf ("This is child\n"); }} return 0;}

The result of this operation: This is the childwill print 80 times the sentence.

First problem: Redundant duplicate I/O output

I/O outputs, there is an I/O buffer (a special memory area) that releases the buffer contents (emptying the buffer) only after the buffer content is completely output to the I/O device.

I/O devices are low-speed devices relative to CPU and memory, which is why buffers are needed (preventing slow devices from slowing down high-speed device performance), which makes it possible to copy a buffer to a child process when it is forked when it is not released in a timely manner. The child process then repeats the contents of the buffer to the I/O device output.

This is why you see the duplicate printing.

The buffer has a size.

The solution to this problem needs to study the device buffering method, there are three kinds of buffering methods of the devices under Linux:

(1), full buffer: the output of the I/O is written directly to the buffer, does not reach the device until the buffer is full, the entire buffer space will be released once, the data sent to the I/O device.

(2), line buffer: The output of the I/O is written directly to the buffer, does not reach the device until the new data is met to return a newline character or buffer full, the data is sent to the I/O device, releasing the entire buffer space or before the carriage return to the content before the line break.

(3), unbuffered: Buffer size is 0, data is sent directly to I/O device.

The Setbuf () method family can adjust the buffer size.

Fflush () releases (empties) the buffer in a timely manner.

To change the above code, clear the buffer:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h>int main (void    ) {pid_t pid;    int i;        for (i = 0; i < 5; i++) {pid = fork ();            if (PID = = 0) {printf ("This is child\n");  Fflush (stdout);        Empties the contents of the buffer. }} return 0;}

The result of the output at this time: Thisis the child prints 31 times and is the correct result .

Second question: How many processes are produced (including the parent process at the beginning)

A total of 2 cycles have been generated in the process. The reason is that every child process that is generated will continue to call fork. This is the process bomb. (Fork resource not available)


10. The demise of the process

The demise of the process: ends the process by calling exit from the system. Although the exit method can not be written in the program, but as long as the process is finished by exit to end, even if the main method execution end, and ultimately exit.

Process Extinction process: the process informs the operating system that the kernel is going to end by calling exit. This is because the management of the PCB is the operating system kernel, the operating system kernel needs to know the end of the process in order to: (1), inform the process of the parent process "your child process to end"; (2), recycle PCB resources.


11, the continuity of the process

(1), the need for PCB management, (2), the process is arrogant, (3), the process is independent, highly closed.

(4), no process exists independently of the process tree.

This article is from the "11586096" blog, please be sure to keep this source http://11596096.blog.51cto.com/11586096/1852992

Linux process Environment

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.