现在的位置: 首页 > 综合 > 正文

(转自朱云翔老师)关于malloc和fork的思考

2013年05月02日 ⁄ 综合 ⁄ 共 860字 ⁄ 字号 评论关闭

 

该文章转自朱云翔老师博客:zhuyunxiang.csai.cn/

在父进程malloc的地址空间,fork之后,在子进程中是copy一份,还是共享呢?

写一段程序试验一下:

Code:
  1. #include <stdio.h>  
  2. #include <sys/types.h>  
  3. #include <unistd.h>  
  4. #include <stdlib.h>  
  5. #include <string.h>  
  6.   
  7. int main()  
  8. {  
  9.     char *p = (char*)malloc(10);  
  10.     strcpy (p, "ccc");  
  11.     printf ("p address:%p, p = %s/n", p, p);  
  12.       
  13.     pid_t pid = fork();  
  14.     if (0 == pid)  
  15.     {  
  16.         strcpy (p, "ccc111");  
  17.         printf ("child p address:%p, p = %s/n", p, p);  
  18.         sleep (10);  
  19.         printf ("child p address:%p, p = %s/n", p, p);  
  20.     }  
  21.     else if (pid > 0)  
  22.     {  
  23.         sleep(3);  //让子进程先执行
  24.         strcpy (p, "ccc222");  
  25.         printf ("parent p address:%p, p = %s/n", p, p);  
  26.     }  
  27.   
  28.     free(p);  
  29.     return 0;  
  30. }  

运行结果及分析略了(好像没法粘贴图片)。

分析运行结果,可知子进程确实是copy了一份,但通过%p打印出来的地址值是相同——这只能说明他们的虚拟地址是一样,但父子

进程的物理地址是不一样的。

每个进程都有自己的虚拟地址空间,但不同进程的相同地址空间事实上具有不同的物理块。

抱歉!评论已关闭.