[英]Save data about signal in file?
我試圖將有關信號的某些信息保存在文件中,例如,在信號處理程序中捕獲信號的時間等。
void sig_handler(int signo){
curr_signal = time(NULL);
receivedtime[z] = curr_signal;
signumber = signo;
diff = curr_signal - receivedtime[z-1];
z++;
write(f, &diff, sizeof(diff));
}
我已經更新程序以寫入文件(f)。 我的問題是文件中什么都沒有寫。正在創建文件。
請注意信號處理程序內部的調用。
從man 7 signal
:
Async-signal-safe functions
A signal handler function must be very careful, since processing else‐
where may be interrupted at some arbitrary point in the execution of
the program. POSIX has the concept of "safe function". If a signal
interrupts the execution of an unsafe function, and handler either
calls an unsafe function [...],
then the behavior of the program is undefined.
並遵循異步信號安全功能的列表。
您的信號處理程序調用:
time()
:好的,它是異步信號安全的 fprintf()
:不,不是。 現有的答案告訴您為什么它不起作用:您在信號處理程序中調用信號不安全函數。 我想添加要執行的操作:最好的做法是在處理程序中盡可能少地執行操作,而是將有關信號的信息告知“常規”代碼。 可以使用volatile sig_atomic_t
變量來完成此操作。 只需更新您的數據結構並將volatile sig_atomic_t
設置為1
。 在您的主代碼中,定期檢查該變量,如果已設置,請執行所需的輸出並將其設置回0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.