The fork function of C language in Linux process operation and related questions explain _c language

Source: Internet
Author: User

The meaning of fork

The following figure is the storage space layout of the C program (typical)

1. An existing process can invoke the fork function to create a new process.
The 2.fork function is called once, but returns two times, and the only difference that is returned two times is that the return value of the subprocess is 0, and the return value of the parent process is the PID of the new child process.
3. The child process and the parent process continue to execute the instructions after the fork call.
In the storage space layout of the diagram above, the parent-child process shares only the body segments, and the rest have separate replicas (usually using the Copy-on-write policy, which is faster).

Two ways to use fork
1. The parent-child process executes different code snippets at the same time
Typical application: Web server.
The following code is a simple fork parent-child process that executes separate code:

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

#define ERR_SYS (x) do { Perror (x); Exit (1); while (0)

void invoke_child (char ch)
{
  printf ("%c\n", ch);
}

int main (int argc, char *argv[])
{
  pid_t  pid;

  int   cnt = 3;
  Char  arg[] = "abc";
  while (cnt--) {
    if ((PID = fork ()) < 0) {
      err_sys ("fork Error");
    } else if (PID = = 0) {
      invoke_child (arg[cnt]);
      Exit (0);
    }
  }

  return 0;
}

2. A process has to perform a different procedure
Typical application: Shell.
Here's an example.

A question about Fork's face
Question: How many of the following programs output "-"?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
 
int main (void)
{
  int i;
  For (i=0 i<2; i++) {
   fork ();
   printf ("-");
  }
 
  return 0;
}

If you are familiar with the fork (), the problem is not difficult, the output should be 6 "-", but, in fact, the program will be very tricky output 8 "-".

To clarify this question, we first need to know the characteristics of the fork () system call,

The 1.fork () system call is a system call under Unix that creates a subprocess on its own process. One call, two returns, and if the return is 0, it is a subprocess, and if the return value is >0, the parent process (the return value is the PID of the subprocess) is well-known.

2. Another important thing is that at the Call of Fork (), the entire parent process space is copied to the child process in its original mode, including instructions, variable values, program call stacks, environment variables, buffers, and so on.

So, why does the above program input 8 "-", this is because printf ("-"); The statement has a buffer, so for the above program, printf ("-"), put "-" into the cache, and there is no real output (see "C language Puzzle" in the first question), In fork, the cache is copied to the child process space, so there are two more, 8, not 6.

In addition, to say more, we know that the device under UNIX has the concept of "block device" and "character device", the so-called block device, is a piece of data access to the device, the character device is a device to access one character at a time. Disks, memory are block devices, character devices such as keyboards and serial ports. Block devices generally have caching, while character devices are generally not cached.

For the above question, if we modify the above printf statement as:

printf ("-n");

Or

printf ("-");
Fflush (stdout);

There is no problem (6 "-"), because the program encountered "N", or EOF, or slow central full, or file descriptor closed, or active flush, or program exit, the data will be brushed out of the buffer. It is to be noted that the standard output is the line buffer, so it brushes out the buffer when it encounters "N", but for the disk, "n" does not cause the buffer to brush the action, which is full buffering, you can use SETVBUF to set the buffer size, or use the Fflush brush cache.

I guess some friends may not know fork (), so let's change the above program to the following:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main (void)
{
  int i;
  For (i=0 i<2; i++) {
   fork ();
   Note: The following printf has "n"
   printf ("ppid=%d, pid=%d, i=%d n", Getppid (), Getpid (), i);
  Sleep (10); Let the process stay for 10 seconds so we can view the process tree return
  0 with Pstree.

Therefore, the above program will output the following results, (note: Compiled executable program named fork)

ppid=8858, pid=8518, i=0
ppid=8858, pid=8518, I=1
ppid=8518, pid=8519, i=0 ppid=8518, pid=8519, I=1 ppid=8518, pid=8520, I=1
ppid=8519, pid=8521, I=1
$ pstree-p | grep Fork
|-bash (8858)-+-fork (8518)-+-fork (8519)---fork (8521)

In the face of such a picture you may still not understand, nothing, I good to do in the end, draw a picture to you see:

Note: I used a few colors in the image above, and the same color is the same process. As a result, our Pstree diagram can be as follows: (the color in the following image corresponds to the above figure)

In this way, for printf ("-"); This statement, we can clearly know which child process copied the parent process standard output to slow down the content in the central, which resulted in multiple outputs. (as shown in the figure below, that's my shadow and the two-sided frame of those two sub processes)

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.