我正在撰寫一個 C 程式來在我的 raspberry pi 3b 上運行,它實時監控 CPU 的溫度。
為了避免輪詢,我使用該sys/inotify庫來監視/sys/class/thermal/thermal_zone0/temp檔案更新。
但是,這似乎不會對檔案進行更改。
要測驗這個:
- 我
cat在運行 main 時反復輪詢檔案(使用),我看到檔案中的值確實發生了變化,但 main 未檢測到該變化。 - 我試過了
tail -f /sys/class/thermal/thermal_zone0/temp,但這也沒有檢測到任何變化。 - 我創建了一個腳本來定期寫入另一個檔案,并讓我的程式觀察這個檔案,它檢測到那里的變化。
是否有可能在不傳播可由 inotify 檢測到的事件的情況下更新此檔案?我試圖避免不惜一切代價執行此檔案的定期輪詢以監視更改。
溫度監視器.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";
};
};
};
主程式
#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)
}
}
uj5u.com熱心網友回復:
它不是一個真正的檔案,每當您閱讀它時,都會要求驅動程式生成其中的資料。當其內容發生變化時,無法獲得通知。投票就是答案。
https://www.kernel.org/doc/html/latest/filesystems/sysfs.html
在 read(2) 上,show() 方法應該填滿整個緩沖區。回想一下,一個屬性應該只匯出一個值或一組相似值,所以這不應該那么昂貴。
這允許用戶空間隨意對整個檔案進行部分讀取和前向搜索。如果用戶空間尋回零或執行偏移量為“0”的 pread(2),則將再次呼叫 show() 方法,重新啟動,以填充緩沖區。
您不必每次都打開和關閉它,尋找開始應該重繪 它。雖然這可能不會節省多少。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329593.html
上一篇:如何在頭檔案中使用前處理器陳述句取決于包含它的C 檔案
下一篇:使用指標演算法的最大值二維陣列
