detecting the memory page size

前端 未结 7 1983
野性不改
野性不改 2021-02-08 13:31

Is there a portable way to detect (programmatically) the memory page size using C or C++ code ?

7条回答
  •  梦如初夏
    2021-02-08 13:55

    Yes, this is platform-specific. On Linux there's sysconf(_SC_PAGESIZE), which also seems to be POSIX. A typical C library implements this using the auxiliary vector. If for some reason you don't have a C library or the auxiliary vector you could determine the page size like this:

    size_t get_page_size(void)
    {
        size_t n;
        char *p;
        int u;
        for (n = 1; n; n *= 2) {
            p = mmap(0, n * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
            if (p == MAP_FAILED)
                return -1;
            u = munmap(p + n, n);
            munmap(p, n * 2);
            if (!u)
                return n;
        }
        return -1;
    }
    

    That's also POSIX, I think. It relies on there being some free memory, but it only needs two consecutive pages. It might be useful in some (weird) circumstances.

提交回复
热议问题