#include <errno.h>
#include <time.h>
#include <signal.h>
void signal_int(int signo)
{
printf("signal:%d\n", signo);
}
int better_sleep (double sleep_time)
{
struct timespec tv;
/* Construct the timespec from the number of whole seconds... */
tv.tv_sec = (time_t) sleep_time;
/* ... and the remainder in nanoseconds. */
tv.tv_nsec = (long) ((sleep_time - tv.tv_sec) * 1e+9);
while (1)
{
/* Sleep for the time specified in tv. If interrupted by a
signal, place the remaining time left to sleep back into tv. */
int rval = nanosleep (&tv, &tv);
if (rval == 0)
/* Completed the entire sleep time; all done. */
return 0;
else if (errno == EINTR)
/* Interrupted by a signal. Try again. */
continue;
else
/* Some other error; bail out. */
return rval;
}
return 0;
}
static void signal_int(int signo);
static int better_sleep (double sleep_time);
int main(int argc, char* argv[])
{
signal(SIGINT, signal_int);
better_sleep(10);
}
static int better_sleep (double sleep_time){
struct timespec tv;
struct timespec tv_rval;
int rval;
int rval;
/* Construct the timespec from the number of whole seconds... */
tv.tv_sec = (time_t) sleep_time;
/* ... and the remainder in nanoseconds. */
tv.tv_nsec = (long) ((sleep_time - tv.tv_sec) * 1e+9);
另外:man nanosleep:
DESCRIPTION
The nanosleep() function causes the current thread
to be suspended from execution until either the time inter-
val specified by the rqtp argument has elapsed or a signal
is delivered to the calling thread and its action is to
invoke a signal-catching function or to terminate the pro-
cess. The suspension time may be longer than requested
because the argument value is rounded up to an integer mul-
tiple of the sleep resolution or because of the scheduling
of other activity by the system. But, except for the case of
being interrupted by a signal, the suspension time will not
be less than the time specified by rqtp, as measured by the
system clock, CLOCK_REALTIME.
The use of the nanosleep() function has no effect on the
action or blockage of any signal.
我英语不好,其中这一句说的是什么意思:
The suspension time may be longer than requested
because the argument value is rounded up to an integer mul-
tiple of the sleep resolution or because of the scheduling
of other activity by the system.作者: apony 时间: 2007-10-15 17:04 标题: 回复 #2 xiaozhu2007 的帖子 看看你printf的参数...
还有:fedora7下:man nanosleep
DESCRIPTION
nanosleep() delays the execution of the program for at least the time
specified in *req. The function can return earlier if a signal has
been delivered to the process. In this case, it returns -1, sets errno
to EINTR, and writes the remaining time into the structure pointed to
by rem unless rem is NULL. The value of *rem can then be used to call
nanosleep() again and complete the specified pause.
里面有这一句:The value of *rem can then be used to call
nanosleep() again and complete the specified pause.在这个程序中当10秒内
产生中断信号时,*rem保存的是sleep剩下的时间,那么*rem是如何call nansleep again的呢?