Linux Fork Mechanism reprint

Source: Internet
Author: User

Today a friend went to a good foreign company to interview the Linux development position, the interviewer has a following topic:

Give the following C program, using GCC to compile under Linux:

1234567891011121314 #include "stdio.h" # Include "Sys/types.h" #include "unistd.h"   int  main () {      pid_t pid1;      pid_t Pid2;       pid1 = fork ();      pid2 = fork ();       printf ( "pid1:%d, pid2:%d\n"

Requirements are as follows:

It is known that all processes executed from this program to this program end this time period and no other new processes are executing.

1, please say that after the implementation of this program, will run a total of several processes.

2, if the output of one of the processes is "pid1:1001, pid2:1002", write out the output of other processes (regardless of process execution order).

The objective of this problem is to investigate the implementation mechanism of the fork in Linux. Below we analyze this topic, talk about the running mechanism of the Linux fork.

Pre-knowledge

Here is a list of some of the necessary preliminary knowledge, the Linux process mechanism is more familiar with the friend can skip.

1, the process can be seen as a process of execution of the program. Under Linux, each process has a unique PID identification process. The PID is a positive integer from 1 to 32768, where 1 is typically a special process init, and the other processes are numbered sequentially from 2 onwards. When you are finished with 32768, restart from 2.

2. There is a structure called the process table in Linux to store the currently running process. You can use the PS aux command to view all running processes.

3, the process in the Linux tree structure, init is the root node, the other processes have a parent process, a process of the parent process is the process of initiating this process, this process is called the parent process child process.

4, the role of fork is to replicate a process that is the same as the current process. All the data for the new process (variables, environment variables, program counters, etc.) are consistent with the original process, but are a completely new process and as a child of the original process.

The key to solving problems

With the preparatory knowledge above, let's look at the key to solving the problem. I think the key to solving the problem is to recognize that the fork is cut into two segments. See:

Represents a program that contains a fork, and the fork statement can be seen as cutting the program to A, B, two parts. Then the entire program will run as follows:

Step1, set up by the shell to execute the program directly, generated the process p. P finishes executing part. All the code for a.

Step2, when executing to PID = fork (), p starts a process q,q is a child of P, and P is the process of the same program. Q inherits the current values of all variables, environment variables, and program counters for p.

Step3, in the P process, the fork () returns the PID of Q to the variable PID and proceeds to the part. B's Code.

STEP4, in process Q, assigns 0 to the PID, and continues to execute part. B's Code.

Here are three points that are critical:

1, p executes all programs, and Q only executes part. B, which is the program behind the fork (). (This is because Q inherits the P's pc-program counter)

2. Q inherits the current environment when the fork () statement executes, not the initial environment of the program.

3. The fork () in P starts the sub-process Q and returns the PID of Q, while the fork () statement in Q does not start a new process and returns only 0.

Solving

The following uses the knowledge described above to solve problems. Here I put two questions together for analysis.

1, from the shell to execute this program, started a process, we set this process for P0, set its PID to XXX (the problem-solving process does not need to know its PID).

2, when the execution to Pid1 = Fork (), P0 start a sub-process P1, by the title P1 PID is 1001. We don't care about P1.

3, the fork in the P0 return 1001 to PID1, continue to Pid2 = fork (), at this time to start another new process, set to P2, by the title of P2 PID is 1002. The same goes for the P2.

4, the second fork in the P0 return 1002 to Pid2, continue to execute the follow-up procedure, end. So, the result of P0 is "pid1:1001, pid2:1002".

5, again see P2,p2 Generation, P0 in pid1=1001, so P2 pid1 inherit P0 1001, and as a child process pid2=0. P2 executes after the second fork and outputs "pid1:1001, pid2:0" after the end.

6, then look at the first fork in P1,p1 return 0 to Pid1, and then execute the following statement. The subsequent statement is Pid2 = fork (); execution here, P1 a new process, set to P3. First, regardless of P3.

7, P1 in the second fork will P3 PID return to Pid2, from the preparatory knowledge P3 pid is 1003, so P1 pid2=1003. P1 continues the follow-up process, ending with output "pid1:0, pid2:1003".

8, P3 as a sub-process of P1, inherit P1 pid1=0, and the second fork will return 0 to Pid2, so P3 finally output "pid1:0, pid2:0".

9, to this end, the entire implementation process is complete.

Answer:

1. A total of four processes were carried out. (P0, P1, P2, P3)

2, the output of several other processes are:

pid1:1001, pid2:0

pid1:0, pid2:1003

pid1:0, pid2:0

Further, you can give a process tree rooted in P0:

Verify

Below we go to Linux under the actual implementation of this program, to verify our answers.

Procedures such as:

After compiling and executing with GCC, the results are as follows:

Since we are unlikely to encounter a PID assigned to 1001, the exact value may differ from the answer. But the 2710 here is the base, and the result is consistent with our answer above.

Summarize

It should be said that this is not a particularly difficult or tricky topic, but due to the complexity of the fork function mechanism, the problem becomes complex when the two fork side-by. The key to solve this problem is to have a certain understanding of the mechanism of Linux under the process, the second is to seize the above mentioned several key points on the fork. The friend said, this question gives the time is 5 minutes, should say the time is abundant, but in the interview occasion, still is very test a person to the process, the Fork Mastery degree and the field reasoning ability.

I hope this article can help friends have a clear understanding of the implementation mechanism of fork.

Linux Fork Mechanism reprint

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.