Linux (1): fork function

Source: Internet
Author: User
Tags function prototype terminates

PS: Every blog but in order to record the process of learning, and reflect on the summary, if there are errors, but also to correct .


Function prototype: extern __pid_t fork (void) __thrownl;

The function is included in the header file unistd.h.

Gaze in the source file:

/* Clone The calling process, creating an exact copy. Return-1 for errors, 0 to the new process,

And the process ID of the new process to the old process. */

Fork () produces a child process. Its child processes replicate the data and stack space of the parent process. and inherits the user code, group code, environment variables, open file codes, working folders, and resource limits of the parent process.

Linux uses Copy-on-write (COW) technology, only when one of the processes attempts to change the space to be copied to do a real copy action, because these inherited information is copied, not the same memory space, so the child process changes to these variables and the parent process is not synchronized.

In addition Child processes do not inherit file locks and unhandled signals from the parent process. (Cow is not so perfect. Cow is a very important optimization method, the core is lazy processing entity resource requests. There is only a shared resource between multiple entity resources, at first it does not actually implement a copy of the resource, but only when the entity has to make changes to the resource to actually assign the entity a private resource. But Cow technology also has its advantages and disadvantages.

The 1.COW Technology Division reduces the instantaneous delay in allocating and replicating large amounts of resources, but actually attaches such delays to the operations that might be required.

2.COW Technical section reduces unnecessary resource allocation. For example , when the fork process. Not all pages need to be copied, and the parent process's code snippet and read-only data segment are not modified, so no duplication is required.

Note that Linux does not guarantee that child processes run first or late than the parent process. So be aware of the deadlock or the race condition when you tap code.


Return value: Assuming that the fork () call succeeds, the parent process returns the newly established child Process Code (PID). In the newly created child process, 0 is returned.

If fork () fails, it returns 1 directly, and the reason for failure is in errno. There are three reasons for failure:

1) system memory is not enough;

2) The process is full (capacity is generally 200~400).

3) The user has too many child processes (typically no more than 25).

Error code: Eagain memory is insufficient, ENOMEM memory is insufficient to configure the data structure space required by the core.

The new process that fork creates is called a subprocess (child process).

The function is called once, but returns two times. The difference of two returns is that the return value of the child process is 0, and the return value of the parent process is the process IDof the new process (child process).

The child processIDthe reason for returning to the parent process is that because a process can have more than one child process, there is not a single function that enables a process to obtain all of its child processesID。 For a sub-process, the reasonForkreturn0give it, is because it is ready to callGetpid ()to get their ownPID. can also callgetppid ()to get the parent process'sID。(ProcessID 0always used by the swap process. So the process of a child processIDImpossible for0).

To give a sample example:

#include <stdio.h> #include <unistd.h> #include <stdlib.h>int main () {int pid;pid=fork ();p rintf (" Hello\n "), if (pid==0) printf (" I ' m child process.\n "); elseprintf (" I ' m parent process.\n "); return 0;}

The result of the operation is:


    Forklater,The operating system replicates a child process that is completely the same as the parent process. Although the relationship between father and son. But in the operating system it seems that they are more like brotherly relationships. This2process to share a code space. Because the child process is a copy of the parent process. So it has a copy of the parent process data space, stack, and heap. They do not share these storage spaces. They only share body segments. However, the data space is independent of each other, the content in the child process data space is the full copy of the parent process, the instruction pointer is also exactly the same, the child process has the parent process currently executing to the location(Two process of program counterPCthe value is the same, i.e.. Child processes are fromForkreturned at the start of the execution), but with a little difference, supposeForksuccess. In a child processForkThe return value is0. In the parent processForkThe return value is the process number of the child process, assumingForknot successful. The parent process will return an error.

#include <unistd.h> #include <stdio.h>int a=5;int main () {   int b=6,pid;   PID =fork ();   if (pid<0)   {      printf ("error\n");   }   else if (pid==0)   {      a++;      b++;      printf ("Child process:%d\n", Getpid ());      printf ("%d%d%d\n", Getpid (), b);   }   else   {      printf ("Parent process:%d\n", Getpid ());      printf ("%d%d%d\n", Getpid (), b);   }}

Operation Result:


As a result, the value of the child process has changed. Can explain. They are not shared.

Then look at the address of the variable:

#include <unistd.h> #include <stdio.h>int a=5;int main () {   int b=6,pid;   PID =fork ();   if (pid<0)   {      printf ("error\n");   }   else if (pid==0)   {      a++;      b++;      printf ("Child process:%d\n", Getpid ());      printf ("%d%d%d%p%p\n", Getpid (), a,b,&a,&b);   }   else   {      printf ("Parent process:%d\n", Getpid ());      printf ("%d%d%d%p%p\n", Getpid (), a,b,&a,&b);}   }

Operation Result:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /southeast ">

As can be seen from the results, the variable address is the same!

! The content is not the same, because the address of the printed variable is logical space for the parent-child process. Their logical space is the same as the virtual address , but the physical space is still different. each process has a separate 4G virtual address space, mapped to a different physical space. For example, I'm doing two processes at the same time, and they all have access to their own virtual addresses, but the physical memory after the mapping will not be the same address.

So in multi-process programming. Do not expect to infer two variables by address.

So, two processes were executed at the same time, and Unison, after the fork , they worked differently. That's the bifurcation. This is also the reason why Fork is called fork , as for that one is executed first. may be related to the operating system (scheduling algorithm), and this problem is not important in practical applications. It is assumed that the parent-child process can be solved by means of the primitive language .

Finally, look at the relationship of the parent-child process. See online someone said:

Their relationship is a management and managed relationship when the parent process terminates. The child process also terminates with it. But the child process terminates. The parent process does not necessarily terminate. For example, when Httpdserver executes, we can kill its child process, and the parent process is not terminated because of the child process termination. In Linux process management, when we find a process that consumes too much resources or cannot be controlled. It should be killed to protect the system's stable and secure execution.

We are able to verify the correctness of the procedure by checking:

#include <stdio.h> #include <unistd.h> #include <stdlib.h>int main () {   int pid,v=1;   Pid=fork ();   if (pid==0)   {      printf ("Child process:pid=%d,ppid=%d,v=%d\n", Getpid (), Getppid (), v++);      Sleep (1);      printf ("Child process:pid=%d,ppid=%d,v=%d\n", Getpid (), Getppid (), v++);      Exit (0);   }   else   {      printf ("Parent process:pid=%d,ppid=%d,v=%d\n", Getpid (), Getppid (), v++);  }

Operation Result:

Be able to see that the parent process exits first, and the PPID of child before exiting is 6707. The PPID of the subprocess becomes 1613 after exiting . The PS command looks to 1613 as the Init process, stating that the child process after the parent process exits is determined by the Init Process adoption. The child process does not exit .




Linux (1): fork function

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.