简体   繁体   中英

C++ mincore return vector every byte is 1

I use mincore to judge memory by mmap open in memory or disk. but return a set vector. Why? In fact the result must be a all clear vector, but I get all set.

This is my code. Why is line 28 ( cout << "find" << endl; ) always skipped?

/proc/pid/smap can see RSS is 0, but mincore return total file in memory.

#include <iostream>
#include <unistd.h>
#include <sys/mman.h>
#include <bitset>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

using namespace std;

int main()
{
    char* pData1 = NULL;
    int fd1 = open("test_large_file_1", O_RDWR);
    if (fd1 == -1)
    {
        cout << "file error ..." << endl;
        return -1;
    }
    off_t size1 = lseek(fd1, 0, SEEK_END);
    if (size1 == -1)
    {
        cout << "lseek error ..." << endl;
        return -1;
    }
    pData1 = (char *)mmap(NULL, size1, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd1, 0 );
    if (pData1 == MAP_FAILED)
    {
        cout << "mmap error ..." << endl;
        return -1;
    }
    unsigned char *pVec = new unsigned char[size1 / 1024 / 4];
    if (-1 == mincore(pData1, size1, pVec))
    {
        cout << "mincore error ..." << endl;
        return -1;
    }
    for (int i = 0; i < size1 / 1024/ 4; ++i)
    {
        if (i % 1000 == 0)
            cout << (int)pVec[i] << endl;
        if ((pVec[i] & 1) == 0)
        {
            cout << "find" << endl;
            break;
        }
    }
    close(fd1);
    munmap((void *)pData1, size1);
    return 0;
}

I want to get whether an address by mmap opening in memory or not, veteran has some way?/ I need help.

I get a old file(don't open long time),mincore return a normal vector(has 0 and 1), but a new file(just now open or read ...),mincore return a all set bit vector. This phenomenon is due to page cache, that will save recently page to cache, if a program repeatly open a file, the page of file will be get in memory .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM