Why does mmap file use more memory than file size?

I am experimenting with mmapand came up with the following code example:

    int main() {

    int fd;
    char *filename = "/home/manu/file";
    struct stat statbuf;
    int i = 0;
    char c = *(filename);

    // Get file descriptor and file length
    fd = open(filename, O_RDONLY);
    if (fd == -1) {
        perror("fopen error");
    }
    if (fstat(fd, &statbuf) < 0) {
        perror("fstat error");
    }
    printf("File size is %ld\n", statbuf.st_size);

    // Map the file
    char* mmapA = (char*) mmap(NULL, statbuf.st_size, PROT_READ, MAP_PRIVATE,
            fd, 0);
    if (mmapA == MAP_FAILED) {
        perror("mmap error");
        return 1;
    }

    // Touch all the mapped pages
    while (i < statbuf.st_size) {
        c = mmapA[i];
        i++;
    }
    c++;

    // Close file descriptor
    if (close(fd) == -1) {
        perror("close");
        return 1;
    }

    //Unmap file
    munmap(mmapA, statbuf.st_size);

    return EXIT_SUCCESS;
}

File size: 137948 bytes = 134.7 kilobytes. To check the program memory, I use the upper, mainly RES and VIRT columns. I look for these values ​​in three different places:

  • before calling mmap
  • right after the call mmap
  • after reading all the associated memory so that the file is loaded into main memory (after page errors)

The value shown above

  • VIRT = 1828 RES = 244
  • VIRT = 1964 RES = 248
  • VIRT = 1964 RES = 508

1964 - 1828 = 136, I think, in kilobytes and, thus, perfectly fits the file size.

But I can not understand the difference RES 508 - 248 = 260 .. Why is it different from the size of virtual memory and file size?

+3
1

: , . 136 , , - , . , . 344 480 , 348 . SHR: 136 .

( 136 ), , , dd .

pmaps, mmap().

RES , . , a.out. 10 mmap() 10 munmap(). . /proc, . ,

./a.out

:

for ((i=0;i<4;i++)); do cat /proc/$(ps -fe | egrep '[a]\.out' | awk '{print $2}')/smaps > smaps.$i; sleep 5; done

4 . , . 1 2, [, , ]:

user@machine:~$ diff -u smaps.{1,2}
--- smaps.1     2012-04-19 00:01:46.000000000 +0200
+++ smaps.2     2012-04-19 00:01:51.000000000 +0200
@@ -84,13 +84,13 @@
 MMUPageSize:           4 kB
 b782f000-b7851000 r--p 00000000 08:05 429102     /tmp/tempfile
 Size:                136 kB
-Rss:                   0 kB
-Pss:                   0 kB
+Rss:                 136 kB
+Pss:                 136 kB
 Shared_Clean:          0 kB
 Shared_Dirty:          0 kB
-Private_Clean:         0 kB
+Private_Clean:       136 kB
 Private_Dirty:         0 kB
-Referenced:            0 kB
+Referenced:          136 kB
 Swap:                  0 kB
 KernelPageSize:        4 kB
 MMUPageSize:           4 kB

, , : , 136 kB - .

diff RES - (s), Rss. - , , , , [heap] [stack]. nos .

+2

All Articles