From: http://cc.byexamples.com/20070525/nanosleep-is-better-than-sleep-and-usleep/
Don’t know whether you aware of the example code at Tap the interrupt signal, I am using sleep(1) within endless loop at the first sample of code.
The example of the code is to illustrate the tapping Interrupt signal while I hit control+c and ignores the termination of the program. When I hit control+c, I discover a problem. the sleep process elapse straight away although its not yet pass a second where it support to sleep for one second.
It happens to usleep function as well, where both sleep and usleep doesn’t seems to be a good sleep function to use. And I discover a better sleep function from time.h. That is nanosleep. Refers to nanosleep man page, it briefly state that it can cater the problem by storing the remaining time at second param, and with that you can use the remaining to to call nanosleep again.
That means, its not like sleep or usleep, you can use it straight away. Well, I have write a wrapper for miliseconds sleep. With the signal tap handler function in sample code, use to test for usleep and my own msleep.
__nsleep is a wrapper for nanosleep, the reason I want to do that wrapper is because I want to make a recursive call to nanosleep. If nanosleep is intercept by signal, it will return -1 and the second param will store the remaining time. With that, I call __nsleep recursively passing the second param as first param now. The second param will be a temp timespac structure variable.
I create another wrapper msleep accepting millisecond, in timespec structure, you can either gives value in nanosecond or second. One thing to be aware is tv_nsec cannot go beyond 999999999, which is 1 second. If beyond that, you have to put it into tv_sec.
Updates:
I found __nsleep() is redundant, and I have a better idea without using recursive and __nsleep at all, instead, directly create a msleep.
Store back the remaining time to req, If getting return value -1, continue to sleep. Better and cleaner isn’t it? :D