我无法使用 fstream 读取 MSR(模型特定寄存器)。为什么会这样?
使用 fopen/fseek/fread 读取效果很好。
有人知道为什么吗?以下是 MSR 的特权。
# ll /dev/cpu/0/msr
crw------- 1 root root 202, 0 Jan 26 22:29 /dev/cpu/0/msr
最佳答案
C++ buffers I/O 读取和写入。例如,在一个简单的 GCC 应用程序中,此缓冲区设置为 8192 字节。当然,您可以更改该大小。
作为 setbuf 上的 Wiki 页面说:
GCC 4.6 libstdc++
With a user-provided buffer, reading from file reads n-1 bytes at a time.
Clang++3.0 libc++
With a user-provided buffer, reading from file reads largest multiples of 4096 that fit in the buffer.
这就是为什么一个简单的 open
、seek
、read
从 GCC 编译程序转换为:
openat(AT_FDCWD, "/dev/cpu/0/msr", O_RDONLY) = 3
lseek(3, 408, SEEK_SET) = 408
read(3, 0x113a0a0, 8191) = -1 EINVAL (Invalid argument)
注意值 8191。EINVAL
背后的答案由 MSR(4) 提供。 :
The register access is done by opening the file and seeking to the MSR number as offset in the file, and then reading or writing in chunks of 8 bytes.
最简单的修复方法是更改缓冲区的大小。在 GCC 中,您可以这样做:
char buf[8 + 1];
std::ifstream file;
file.rdbuf()->pubsetbuf(buf, sizeof(buf));
file.open("/dev/cpu/0/msr", std::ifstream::binary);
关于c++ - fstream 读取 MSR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904423/