關於linux信號對sleep的影響與相關對策

關於linux信號對sleep的影響

首先想說用sleep來定時是不靠譜的
簡單記錄一下

當前有個功能,底層傳遞一個信號上來,然後linux應用會調用相關的中斷處理函數。但是每次觸發了信號,主程序裏面sleep函數就直接退出了。主程序就亂了。

那麼首先想的是爲什麼sleep會退出?

NAME top
       sleep - sleep for a specified number of seconds
SYNOPSIS top
       #include <unistd.h>
       unsigned int sleep(unsigned int seconds);
DESCRIPTION top
       sleep() causes the calling thread to sleep either until the number of
real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.
RETURN VALUE top
       Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.
ATTRIBUTES top

返回值:
Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

這裏說明了sleep的確是有這個機制的,只要來信號就會退出,並返回剩餘值。

那麼方法就有了:
只要把剩餘的時間在sleep過去就好了
但是進過測試發現,這個方法不是很靠譜,應爲如果我sleep了1.1s,就直接退出,那麼就等於少延時了0.9s。

那就用usleep(10000000),延時10s來做。
but 看了下發現並不能正常使用,因爲usleep和sleep不同,他不會返回剩餘時間。0正確-1錯誤。

這樣的話,10s就直接過去了。

最終那麼就時間切片 1000次每次usleep(10000),每次就算是退出了我也不管他,退出一次也就是10ms。

最終沒有解決這個問題,只是繞過了他。
如果有更好的方法請告知多謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章