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内存区域的关系。