printf ("We want to sleep until sec=%ld nsec=%ld\n",
ts.tv_sec, ts.tv_nsec);
ret = clock_nanosleep (CLOCK_MONOTONIC, TIMER_ABSTIME,
&ts, NULL);
if (ret)
perror ("clock_nanosleep");
多數程式只需要進行相對的休眠,因為它們的休眠時間並不需要非常精確。然而,有些
即時行程有非常確切的時序要求,而且需要進行絕對的休眠,以避免可能的爭用情況。
以可移植的方式進行休眠
現在召回我們在第2章的好朋友
select()
:
#include <sys/select.h>
int select (int n,
fd_set *readfds,
fd_set *writefds,
fd_set *exceptfds,
struct timeval *timeout);
如第2章所述,以亞秒的解析度(sub-second resolution)進行休眠時,若考慮到移植
性,可以使用
select()
。長久以來,可移植的Unix程式都一直在使用
sleep()
來提出它
們需要的休眠時間:
usleep()
並非隨處可用,而且
nanosleep()
尚未被寫出來。開發者
發現,想讓行程進入休眠狀態時,若把
0
傳入
select()
的
n
,把
NULL
傳入三個
fd_set
指
標,以及把所需要的休眠時間傳入 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.