Fork () sub-process function usage and related problems of C language in Linux _c language

Source: Internet
Author: User

Fork
the fork () function is a system call under Linux that produces a child process that is a copy of the current process and has the same virtual content as the parent process, but there are some differences.
However, it is noteworthy that after the parent process calls fork (), fork () returns the ID of the generated child process (if it can be generated). The starting point of the subprocess execution is also the location of the fork in the code, and the following C language code shows how the fork () function is used:

MYFORK.C

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

int main (int argc, char **argv) {while
  (1) {
    pid_t pid = fork ();
    if (PID > 0) {
      //main process Sleep
      (5);
    } else if (PID = = 0) {
      //child process return
      0;
    } else {
      Fprin TF (stderr, "fork error\n");
      return 2;}}}


When the fork () function is invoked, the system copies the vast majority of the resources of the current process (where the Copy-on-write technology is not detailed here), and the return value of the function is three cases, respectively:
1. Greater than 0, indicating that the current process is a parent process, and that the return value is a child process number;
2. Equals 0, indicating that the current process is a child process;
3. Less than 0 (exactly equal to 1) indicates that the fork () call failed.

Look at two more interesting C language topics.

The first question: calculate the following code in theory, the total number of lines printed: (NetEase 2011 questions)

#include
#include
#include
int main () {
    int i;
    for (i = 0; i<5; i++) {
        fork ();
        printf ("%d\n", Getpid ());
        Fflush (stdout);
    }

Question Answer:
This problem is not difficult, the quickest idea is 2+4+8+16+32, because the first level of printf will have two process printing, the second layer will be increased to 4, as a result, 62 lines.

But I'm going to use another method, a more intuitive way, is to just count it out, which will prevent the brain from short-circuiting and help with the next topic.

It's also simple to count directly, but it's a bit cumbersome because each time the loop is printed and a child process is generated, the child process continues to cycle through the print and generate a new process. We can draw a tree on the draft paper, draw the sub process of each process and the number of cycles, if you have good eyesight, the brain is not easy to mess, this method will soon let you get the correct answer. But I happen to be the brain is not to be able to ensure sober people, painted three times the tree is the wrong answer.

Then I used a simpler data structure--a queue--to calculate the paper, and I got the answer smoothly. That's how I calculated it:

First, the main process loops 5 times, then we press 5 into the queue:

Queue = "5";
sum = 0; Sum is the total number of prints

The main process loops 5 times, prints 5 rows and produces 5 child processes, which print 5,4,3,2,1 rows, then we put the 5 numbers in the queue and add the first 5 out queue to sum:

Queue = "5 4 3 2 1";
sum = sum + 5;

So, we take the first element of the queue, that is, 5, he prints 5 lines and generates 4 children, and the child process prints the 4,3,2,1 row, we put the 4 numbers into the queue and add the first 5 out queue to sum:

Queue = "4 3 2 1 4 3 2 1";
sum = sum + 5;

We continue to repeat the above work, take the first element 4, he will print 4 lines, and will claim 3 child processes, the child process printing 3,2,1 row, repeat the above queue and out queue operations:

Queue = "3 2 1 4 3 2 1 3 2 1";
sum = sum + 4;

In this way, repeat the above operation, when the element 1 is encountered, only out of the queue and not into the queue operation, because only 1 rows of child processes will not be recycled to produce new child processes. Finally, when there are no more elements in the queue, sum is the number of rows that are printed altogether.

A bit of this approach is that you can easily and very clearly in the paper to write out the queue and calculate the answer, the disadvantage is that if you add bad, it is easy to calculate the wrong answer!

Question number Two: how many processes (excluding the main process) were generated after the following code was executed? (2009 EMC written)

#include
int main () {
    fork ();
    Fork () && fork () | | Fork ();
    Fork ();
}

This topic is a little more difficult to compare with the previous one, because you may be wrong even if you draw a tree!

I personally feel that this topic examines two aspects of knowledge: 1, the fork () return value at the beginning, 2, && and | | The operation.

Let's now discuss the && and | | To continue the discussion of this topic. && is a "logical and" operation, and if two operands have one 0, the entire formula is 0. Standard C stipulates that if the left operand of the && operator is 0, the right operand is not computed, and the right operand is calculated if the left operand is 1.
Similar to, | | The operator is a "logical or" operation, and standard C stipulates that if | | The left operand of the operator is 1, the right operand is not computed, and the right operand is computed if the left operand is 0.

To continue to see our topic, we mark the 5 fork () in the topic as A,b,c,d,e respectively. We can see that the main process produces 4 processes, which are generated in the a,b,c,e position (b,c two fork () return values are not 0, so the b&&c is not 0 and therefore does not compute D). Let's still use the algorithm in the previous question, using a queue:

First, place the main process to produce the child process in the queue:

Queue = "A B C E";
sum = 0;

We take the first element a from the queue, we analyze the process generated by a, and we find that it will produce a subprocess in B, C, E, and we insert the three elements into the queue and we will sum+1.

Queue = "B c e b c e";
sum + +;

We then take the first element out of the queue b,b the resulting subprocess is slightly different because the fork () return value represented by B in the subprocess is 0, so C is not executed, and D is executed. Therefore, the resulting subprocess of B executes D, E, and sends the two elements into the queue, sum++:

Queue = "C e B c e D e";
sum + +;

Below, we take the first element C, and the analysis finds that the process produced by C will execute D, E, fed into the queue and sum++:

Queue = "E B C e d e d e";
sum + +;

As in the previous question, this is done in turn, and if you encounter E, there is no element in the queue until the last queue is empty, and sum is the total number of processes produced.

Related Article

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.