我正在尝试从/proc/<pid>/smaps我的 C++ 二进制文件中解析进程的 PSS 值。
根据这个 SO answer,/proc/<pid>/smaps例如天真地读取文件ifstream::getLine()将导致数据集不一致。建议的解决方案是使用read()系统调用一次性读取整个数据,例如:
#include <unistd.h>
#include <fcntl.h>
...
char rawData[102400];
int file = open("/proc/12345/smaps", O_RDONLY, 0);
auto bytesRead = read(file, rawData, 102400); // this returns 3722 instead of expected ~64k
close(file);
std::cout << bytesRead << std::endl;
// do some parsing here after null-terminating the buffer
...
Run Code Online (Sandbox Code Playgroud)
我现在的问题是,尽管我使用了 100kB 的缓冲区,但只返回了 3722 个字节。查看cat使用 strace 解析文件时的作用,我看到它使用多次调用read()(每次读取时也获取大约 3k 字节)直到read()返回 0 - 如文档 …