Re: fork, copy-on-write and free
From: David Schwartz (davids_at_webmaster.com)
Date: 07/22/03
- Next message: Ernst Murnleitner: "how to set time and rtc clock"
- Previous message: David Schwartz: "Re: Socket keepalive timers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 21 Jul 2003 16:18:19 -0700
"Clemens Resanka" <clemens@NOSPAMcubicle.at> wrote in message
news:m2d6g4ezot.wl@chello080110088192.506.15.tuwien.teleweb.at...
> According to `man 2 fork`, linux uses copy-on-write. Afaik this means,
> that memory will not be allocated until the child process writes to a
> page.
Or the parent process!
> So I alloc 50MB, fork and let mum and child write to their
> respective memory. So the memory usage should be 100MB, right? But it
> isn't. It's 50MB.
It can grow to 100Mb as each process makes modifications. The
copy-on-write takes place on a page-by-page basis.
> Here's some nasty C code:
> ---------------------------
> #include <stdlib.h>
> #include <stdio.h>
> #include <sys/types.h>
> #include <unistd.h>
> #include <sys/wait.h>
>
> int main(int argc, char *argv[]) {
> int i;
> void * mem = malloc((size_t) 50*1024*1024);
>
> if (fork() == 0) {
> printf("child: writing memory\n");
> for (i=0; i<50*1024*1024; i++) {
> *((unsigned char *) mem+i)=1;
> }
>
> free(mem);
> sleep(100);
> printf("child: I'm dying\n");
> exit(0);
> }
>
> printf("mum: I've just given birth\n");
>
> printf("mum: writing memory\n");
> for (i=0; i<50*1024*1024; i++) {
> *((unsigned char *) mem+i)=0;
> }
>
> wait(NULL);
> printf("mum: My child has died. No reason left to live\n");
>
> free(mem);
> }
For large memory blocks, glibc uses 'mmap'. So the 'free(mem)' unmaps
half the memory, allowing the system to discard it.
> So why is that program only using 50MB?
Because one process has released its 50Mb.
> And why is /proc/PID/maps showing the same for both processes?
> Shouldn't that differ as soon as the copy-on-write mechanism comes
> into place?
That shouldn't be. The parent should be missing the 50Mb mapping as soon
as it calls 'free'.
DS
- Next message: Ernst Murnleitner: "how to set time and rtc clock"
- Previous message: David Schwartz: "Re: Socket keepalive timers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|