未检测到温度文件的变化

Change in temperature file not detected

我正在我的 raspberry pi 3b+ 上为 运行 编写一个 C++ 程序,实时监控 CPU 的温度。
为了避免轮询,我正在使用 sys/inotify 库来监视 /sys/class/thermal/thermal_zone0/temp 文件更新。

但是,这似乎没有对文件进行更改。


测试一下:

是否有可能在不传播 inotify 检测到的事件的情况下更新此文件? 我试图避免实施此文件的定期轮询以不惜一切代价监视更改。

temperatureMonitor.cpp

#include <iostream>
#include <unistd.h>
#include <sys/inotify.h>
#include <sys/types.h>

#include "./temperatureMonitor.hpp"


#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

namespace Performance {
  void TemperatureMonitor::monitor_temperature(void(*callback)(double)){

  };
  void TemperatureMonitor::monitor_temperature_file(){
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN];
    fd = inotify_init();

    wd = inotify_add_watch(fd,"/sys/class/thermal/thermal_zone0/temp" , IN_MODIFY|IN_CREATE|IN_DELETE);

    while (true){

    length = read(fd, buffer, BUF_LEN);
    std::cout << "detected file change\n";   
    };
  };
};

main.cpp

#include "Performance/temperatureMonitor.hpp"

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 ∗ ( EVENT_SIZE + 16 ) )


int main(){

  Performance::TemperatureMonitor tm = Performance::TemperatureMonitor();

  tm.monitor_temperature_file();

  return 0;
};

fwriter.go

package main
import (
    "os"
    "time"
)
func main() {
    f, err := os.Create("foo.txt")
    if err != nil {
        panic(err)
    }
    for {
        f.Write([]byte("test\n"))
        time.Sleep(time.Second)
    }
}

这不是真正的文件,无论何时读取它,都会要求驱动程序生成其中的数据。当其内容发生变化时,无法收到通知。投票就是答案。

https://www.kernel.org/doc/html/latest/filesystems/sysfs.html

On read(2), the show() method should fill the entire buffer. Recall that an attribute should only be exporting one value, or an array of similar values, so this shouldn’t be that expensive.

This allows userspace to do partial reads and forward seeks arbitrarily over the entire file at will. If userspace seeks back to zero or does a pread(2) with an offset of ‘0’ the show() method will be called again, rearmed, to fill the buffer.

不用每次都打开关闭,搜索到开头应该刷新一下。虽然这可能不会节省多少。