c++ - fstream 读取 MSR

标签 c++ std intel fstream clang++

我无法使用 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.

这就是为什么一个简单的 openseekread 从 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/

相关文章:

c++ - 在 C++ 中使用 libcurl 的 curl 调用的默认超时

c++ - 当新大小小于当前大小时,std::vector::resize() 是否会重新分配?

c - 在 Linux + Intel 驱动程序上启用合成时,OpenGL 应用程序会产生奇怪的效果

c++ - 英特尔 C++ 编译器和 Eigen

c++ - 混合 std::cout 的奇怪输出

linux - AMD OpenCL 编译器忽略内核属性 "work_group_size_hint"

c++ - 可选引用成员——这可能吗?

c++ - 清除 vector 或定义新 vector ,哪个更快

c++ - 如何将 OS X 风格添加到 Qt 应用程序

c++ - 使用元素加载 std::queue<uint8_t*> 的更有效方法?