linux编程中,通过fork函数会创建子进程,创建后根据写时复制策略,父子进程是共享父进程的堆与栈,当父子进程中的一方对内存进行了写操作后,父子进程的内存会分离,各自拥有自己独立的内存:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define STR_SIZE 30
void doInChild(char *str)
{
printf("in child, str:%s\n", str);
}
void doInParent(char *str)
{
printf("in parent, str:%s\n", str);
}
int main()
{
char *strMalloc = 0;
char strLocal[STR_SIZE] = {0};
strMalloc = (char*)malloc(sizeof(char) * STR_SIZE);
if(strMalloc == 0)
{
printf("malloc failed\n");
return -1;
}
snprintf(strMalloc, STR_SIZE, "%s", "this is parent malloc");
snprintf(strLocal, STR_SIZE, "%s", "this is parent local");
pid_t pid = fork();
if(pid < 0)
{//fork failed
printf("fork failed");
}
else if(pid == 0)
{//in child
doInChild(strMalloc);//由