Linux中父子进程Fork与malloc关系示例


Linux中父子进程Fork与malloc关系示例:

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <string.h>   
  4.   
  5. #define SIZE 16   
  6.   
  7. int main()  
  8. {  
  9.     char *data;  
  10.       
  11.     data=(char *)malloc(SIZE);  
  12.     if(data==NULL)  
  13.     {     
  14.         printf("mallco failed!\n");  
  15.         exit(1);  
  16.     }  
  17.   
  18.     char *str="test data";  
  19.     strcpy(data,str);  
  20.     printf("before fork,the data is: %s\n",data);  
  21.     printf("before fork the addr of mem is: %p\n",data);  
  22.       
  23.     int pid;  
  24.     if((pid=fork())==0)//父进程查看分配的内存信息   
  25.     {  
  26.         strcpy(data,"I am parent");  
  27.         printf("In parent,the data is: %s\n",data);  
  28.         printf("In parent,the addr of mem is: %p\n",data);  
  29.           
  30.         sleep(10);  
  31.         printf("In parent,the data is: %s\n",data);  
  32.         printf("In parent,the addr of mem is: %p\n",data);  
  33.     }  
  34.     else  
  35.     {  
  36.         sleep(5);  
  37.         strcpy(data,"I am child");  
  38.         printf("In child,the data is: %s\n",data);  
  39.         printf("In child,the addr of mem is: %p\n",data);  
  40.     }  
  41.   
  42.     free(data);  
  43.   
  44.     return 0;  
  45.   
  46. }  

运行结果:

  1. pine@pine-pc:/home/song/study/C$ ./malloc   
  2. before fork,the data is: test data  
  3. before fork the addr of mem is: 0x9e3a008  
  4. In parent,the data is: I am parent  
  5. In parent,the addr of mem is: 0x9e3a008  
  6. In child,the data is: I am child  
  7. In child,the addr of mem is: 0x9e3a008  
  8. pine@pine-pc:/home/song/study/C$ In parent,the data is: I am parent  
  9. In parent,the addr of mem is: 0x9e3a008  

通过例子说明,mallco之后进行fork,父子进程之间与malloc内存区域的关系。

通过例子可以看出,在fork之后,父子进程中得到的内存区域是各自独立的,父子进程各自的操作相互不会影响。可以看到,fork之后,父进程向内存之写入了 “I am parent”,接着等待一下,子进程写入“I am child”,但打印的结果显示,两个进程的内存区域是独立的,不会受到影响。

有一点值得注意,那就是父子进程打印内存的地址都是一样的但为什么得到的数据确不一样呢?其实,父子进程的地址空间是相互独立的,两个进程都会copy原始的数据,因此dada的值是一样的,这个是个虚拟地址!须要经过映射变换得到实际的物理地址!!但由于父子进程此时拥有了各自独立的进程空间,即使是同样的虚拟地址,当映射到实际的物理内存时,也不会是同一个物理地址,所以不是同一个内存块(物理上)!!!每个进程对同样的虚拟地址映射结果是不同的。不能使用虚拟地址来做为判断的依据。

相关内容