fork() system call and memory space of the process

前端 未结 6 408
一个人的身影
一个人的身影 2020-12-24 08:54

I quote \"when a process creates a new process using fork() call, Only the shared memory segments are shared between the parent process and the newly forked child process. C

6条回答
  •  感情败类
    2020-12-24 09:53

    Quoting myself from another thread.

    • When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an "exec" system call or exits very soon after the fork(). When the child is needed just to execute a command for the parent process, there is no need for copying the parent process' pages, since exec replaces the address space of the process which invoked it with the command to be executed.

      In such cases, a technique called copy-on-write (COW) is used. With this technique, when a fork occurs, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the original copy of the page (which is now no longer shared). This technique is called copy-on-write since the page is copied when some process writes to it.

    • Also, to understand why these programs appear to be using the same space of memory (which is not the case), I would like to quote a part of the book "Operating Systems: Principles and Practice".

      Most modern processors introduce a level of indirection, called virtual addresses. With virtual addresses, every process's memory starts at the "same" place, e.g., zero. Each process thinks that it has the entire machine to itself, although obviously that is not the case in reality.

      So these virtual addresses are translations of physical addresses and doesn't represent the same physical memory space, to leave a more practical example we can do a test, if we compile and run multiple times a program that displays the direction of a static variable, such as this program.

      #include 
      
      int main() {
          static int a = 0;
      
          printf("%p\n", &a);
      
          getchar();
      
          return 0;
      }
      

      It would be impossible to obtain the same memory address in two different programs if we deal with the physical memory directly.

      And the results obtained from running the program several times are...

    enter image description here

提交回复
热议问题