使用 fscanf 从 /sys/class/thermal/ 中的文件读取温度始终返回相同的值

Reading temperature from files in /sys/class/thermal/ with fscanf keeps returning the same value forever

虽然我使用 fgets 得到了更好的结果,但我真的很困惑为什么下面的代码总是给出相同的值(从第二次读取开始)。

以下是最低气温reader。它似乎第一次正确读取但永远输出相同的值,尽管系统温度发生变化。

要进行比较,可以使用命令 watch cat /sys/class/thermal/thermal_zone0/temp

监控当前有效温度

这是代码(使用 g++ filename.cpp 编译):

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

bool shouldStop = false;

void sigHandler(int signo) {
    if(signo == SIGTERM) {
        shouldStop = true;
    }   
    else if(signo == SIGINT) {
        printf("Bye bye");
        shouldStop = true;
    }   
}   

void temperatureReadLoop() {
    FILE *fp;
    fp = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
    int temperature;
    while(!shouldStop) {
        fscanf(fp, "%d", &temperature);
        printf("\ntemperature read : %d", temperature);
        // //rewind(fp);
        fseek(fp, 0, SEEK_SET);
        sleep(1);
    }   
    fclose(fp);
    printf("\nquit\n");
}   

int  main() {

    signal(SIGTERM, sigHandler);
    signal(SIGINT, sigHandler); // STOP WITH [CTRL + C]
    temperatureReadLoop();
 
}

运行 以上结果为无限

    temperature read : 44000
    temperature read : 44000
    temperature read : 44000
    temperature read : 44000
    temperature read : 44000

...尽管温度在变化。 我尝试以不同的方式重置文件搜索位置,但我没有运气。 这几乎就像 fscanf 有它自己的隐藏缓冲区,它没有被重置。

值得注意的是,如果第一次和第二次读取之间的温度发生变化,则变化会通过并且温度值会正确更新,但只有在第一次和第二次读取之间幸运地发生温度变化时才会发生这种情况;在剩余的 运行 时间内保持不变。

我错过了什么?

您应该在 fseek() 之前调用 fflush()

Fseek 将正确处理程序内部的更新,但它不知道外部更改。