C:知道何时读取或写入变量

C: Know when a variable is read or written

目前在 arm Xilinx 开发平台上工作。使用 linux 和 C.

我映射了一些页面。例如a = mmap(...)。我想知道哪些页面最近最少使用,以便我可以将它们复制到其他地方。

linux 内核本身会跟踪 LRU 页面,例如,找出在内存争用时要交换或不交换的页面。

如果你想在你的库中使用它,你可以从用户空间读取 LRU 标志:

  • 迭代要在 /proc/pid/pagemap 中跟踪的虚拟页面条目并记住页面框架编号
  • 从/proc/kpageflags
  • 读取这些页面对应的标志

现在你有几个标志,可以用于你的逻辑:

 3. UPTODATE  page has up-to-date data
              ie. for file backed page: (in-memory data revision >= on-disk one)
 4. DIRTY     page has been written to, hence contains new data
              ie. for file backed page: (in-memory data revision >  on-disk one)
 8. WRITEBACK page is being synced to disk

    [LRU related page flags]
 5. LRU         page is in one of the LRU lists
 6. ACTIVE      page is in the active LRU list
18. UNEVICTABLE page is in the unevictable (non-)LRU list
                It is somehow pinned and not a candidate for LRU page reclaims,
        eg. ramfs pages, shmctl(SHM_LOCK) and mlock() memory segments
 2. REFERENCED  page has been referenced since last LRU list enqueue/requeue
 9. RECLAIM     page will be reclaimed soon after its pageout IO completed
11. MMAP        a memory mapped page
12. ANON        a memory mapped page that is not part of a file
13. SWAPCACHE   page is mapped to swap space, ie. has an associated swap entry
14. SWAPBACKED  page is backed by swap/RAM

this document

中描述了更多标志

还有一个名为 soft-dirty 的功能,专门用于跟踪最近的 写入 (忽略读取)(请参阅 Soft Dirty 文档) .您可以通过 /proc 清除软脏标志并通过 /proc/pid/pagemap 再次读取它们。也许这对您的应用程序也很有用。

您是否考虑过使用 vmstat(8) Report virtual memory statistics

vmstat 报告有关进程、内存、分页、块 IO、陷阱和 cpu[=33= 的信息]. (强调我的)

包括:

Field Description For Slab Mode

cache: Cache name num: Number of currently active objects total: Total number of available objects size: Size of each object pages: Number of pages with at least one active object totpages: Total number of allocated pages pslab: Number of pages per slab

此处 Linux Journal article 更详细地介绍了如何使用 vmstat 来监控 OS 统计数据。以下是摘录:

Using vmstat

vmstat, as its name suggests, reports virtual memory statistics. It shows how much virtual memory there is, how much is free and paging activity. Most important, you can observe page-ins and page-outs as they happen. This is extremely useful.

To monitor the virtual memory activity on your system, it's best to use vmstat with a delay. A delay is the number of seconds between updates. If you don't supply a delay, vmstat reports the averages since the last boot and quit. Five seconds is the recommended delay interval.

To run vmstat with a five-second delay, type:

vmstat 5