Linux中父子进程Fork与malloc关系示例
Linux中父子进程Fork与malloc关系示例
Linux中父子进程Fork与malloc关系示例:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define SIZE 16
- int main()
- {
- char *data;
- data=(char *)malloc(SIZE);
- if(data==NULL)
- {
- printf("mallco failed!\n");
- exit(1);
- }
- char *str="test data";
- strcpy(data,str);
- printf("before fork,the data is: %s\n",data);
- printf("before fork the addr of mem is: %p\n",data);
- int pid;
- if((pid=fork())==0)//父进程查看分配的内存信息
- {
- strcpy(data,"I am parent");
- printf("In parent,the data is: %s\n",data);
- printf("In parent,the addr of mem is: %p\n",data);
- sleep(10);
- printf("In parent,the data is: %s\n",data);
- printf("In parent,the addr of mem is: %p\n",data);
- }
- else
- {
- sleep(5);
- strcpy(data,"I am child");
- printf("In child,the data is: %s\n",data);
- printf("In child,the addr of mem is: %p\n",data);
- }
- free(data);
- return 0;
- }
运行结果:
- pine@pine-pc:/home/song/study/C$ ./malloc
- before fork,the data is: test data
- before fork the addr of mem is: 0x9e3a008
- In parent,the data is: I am parent
- In parent,the addr of mem is: 0x9e3a008
- In child,the data is: I am child
- In child,the addr of mem is: 0x9e3a008
- pine@pine-pc:/home/song/study/C$ In parent,the data is: I am parent
- In parent,the addr of mem is: 0x9e3a008
通过例子说明,mallco之后进行fork,父子进程之间与malloc内存区域的关系。
通过例子可以看出,在fork之后,父子进程中得到的内存区域是各自独立的,父子进程各自的操作相互不会影响。可以看到,fork之后,父进程向内存之写入了 “I am parent”,接着等待一下,子进程写入“I am child”,但打印的结果显示,两个进程的内存区域是独立的,不会受到影响。
有一点值得注意,那就是父子进程打印内存的地址都是一样的但为什么得到的数据确不一样呢?其实,父子进程的地址空间是相互独立的,两个进程都会copy原始的数据,因此dada的值是一样的,这个是个虚拟地址!须要经过映射变换得到实际的物理地址!!但由于父子进程此时拥有了各自独立的进程空间,即使是同样的虚拟地址,当映射到实际的物理内存时,也不会是同一个物理地址,所以不是同一个内存块(物理上)!!!每个进程对同样的虚拟地址映射结果是不同的。不能使用虚拟地址来做为判断的依据。
评论暂时关闭