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.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.