Some Summary of Fork Function

Time:2019-10-9

 

Today, we encounter a problem like this. Assuming that the parent process has a variable S, after fork, whether the address of the variable S in the child process is the same as that in the parent process.

Is it the same?

When you learn the operating system again, you know that fork is a write-time copy, so if the child or parent processes do not modify the variable S, they should

It refers to the same physical memory. If there are modifications, they will point to different physical memory, but the virtual memory address is the same, so in the sub-process.

Output & S and output & S in the parent process, the result is the same.

 

Here are two additional results of the program:

#include "stdio.h"
#include "unistd.h"

 int main()
 {
          int s=5;
          if(fork()==0)
          {
                  //s+=5;
                  printf("child: %d %x\n",s,&s);
          }
         else
         {
                  //s-=5;
                  printf("parent: %d %x\n",s,&s);
          }
          return 0;
 }

Operation results:

 

The above code does not modify the value of S. The following code modifies the value of S and then tests it again.

#include "stdio.h"
#include "unistd.h"

 int main()
 {
          int s=5;
          if(fork()==0)
          {
                  s+=5;
                  printf("child: %d %x\n",s,&s);
          }
         else
         {
                  s-=5;
                  printf("parent: %d %x\n",s,&s);
          }
          return 0;
 }

Operation results: