- 论坛徽章:
- 0
|
原帖由 seskissinger 于 2010-1-8 20:54 发表 ![]()
不需要。fork时,内核让子进程指向父进程的地址空间。当子进程发生写操作时。才把所写页面复制一份给子进程。
关键是子进程要知道自己在做什么
应该是需要的。在fork后,子进程和父进程拥有相同的内容。copy on write只是OS在实现fork是的一种优化方法,从逻辑上来说,在父进程中分配的内存,在子进程中仍然存在,因此子进程需要归还此内存。
在AIX上做了一个实验:
#include <unistd.h>
#include <stdio.h>
void p_mem(pid_t pid)
{
char cmdbuf[256];
printf("\n-------------------------------------------------------------------------------\n");
sprintf(cmdbuf, "svmon -P %d -O summary=basic", pid);
system(cmdbuf);
}
#define BUF_LEN (200 * 1024 * 1024)
int main()
{
char * buf = (char *)malloc(BUF_LEN);
memset(buf, 0, BUF_LEN);
pid_t pid = fork();
if (pid > 0)
{
printf("parent: %d, child = %d\n", getpid(), pid);
free(buf);
p_mem(getpid());
}
else if (pid == 0)
{
sleep(10);
p_mem(getpid());
}
else
{
exit(0);
}
return 1;
} |
编译后运行结果如下:
aix520/tmp/shiyb/fork>MALLOCOPTIONS=disclaim ./a.out
parent: 426126, child = 544814
-------------------------------------------------------------------------------
Unit: page
-------------------------------------------------------------------------------
Pid Command Inuse Pin Pgsp Virtual
426126 a.out 18027 7711 0 18025
aix520/tmp/shiyb/fork>
-------------------------------------------------------------------------------
Unit: page
-------------------------------------------------------------------------------
Pid Command Inuse Pin Pgsp Virtual
544814 a.out 69245 7711 0 69243
aix520/tmp/shiyb/fork> |
从红色部分可以看出,在父进程free内存后,子进程中的内存仍然存在,需要手动free。 |
|