[常规] nanosleep() -- 更精确的延迟 [复制链接] beyes 4220 主题 5152 帖子 3万 积分 GROAD 曲径通幽,安觅芳踪。 积分 30607 发消息 电梯直达 楼主 发表于 2010-8-22 00:08:53 | 只看该作者 原型: #include <time.h> int nanosleep( const struct timespec * req , struct timespec * rem); 说明:此函数将调用进程挂起,直到 req 里所指的时间结束。req 是 struct timespec 结构体的指针。struct timespec 结构体定义如下: struct timespec { time_t tv_sec; /* 秒 */ long tv_nsec; /* 纳秒 */ }; 如果在调用 nanosleep() 睡眠期间被信号所中断,nanosleep() 就会返回 -1,同时设置 errno 为 EINTR,并且会将剩余的时间写入由 rem 所指向同样时 struct timespec 类型的结构体中,如果 rem 为 NULL,就不会记录剩余时间。当信号处理完毕时,还会继续调用 nanosleep() 直到剩余时间用完为止。测试程序: #include <stdio.h> #include <time.h> #include <signal.h> #include <errno.h> void sigfunc ( int sig_no) { int temp = 1000; while ( temp -- > 0) ; } int msleep ( unsigned long milisec , int temp) { struct timespec req = { 0 }, rem = { 0 }; time_t sec = ( int)( milisec / 1000); milisec = milisec - ( sec * 1000); req . tv_sec = sec; /*秒*/ req . tv_nsec = milisec * 1000000L; /*纳秒*/ while ( nanosleep ( & req , & req) == - 1 && errno == EINTR) { printf ( "测试-%d被信号中断,剩余时间为: %ld秒%ld纳秒 \n " , temp , req . tv_sec , req . tv_nsec); continue; } return ( 1); } int main() { struct sigaction sa = { 0 }; sa . sa_handler = & sigfunc; sigaction ( SIGINT , & sa , NULL); //安装信号处理函数 unsigned long a = 0; int temp = 1; scanf ( "%ld" , & a); for (;;) { if ( a == 5) { printf ( "testing-%d \n " , temp); msleep ( a * 1000 , temp); //将 nanosleep() 封装在 msleep() 中 temp++; } else usleep ( 1000000); } return ( 1); } 运行与输出: $ ./nanosleep 5 testing-1 testing-2 ^C测试-2被信号中断,剩余时间为: 4秒120263116纳秒 ^C测试-2被信号中断,剩余时间为: 3秒440359866纳秒 ^C测试-2被信号中断,剩余时间为: 2秒320431341纳秒 ^C测试-2被信号中断,剩余时间为: 1秒320495448纳秒 testing-3 ... ... 上面,^C 表示按下 Ctrl + c 组合键,发出中断函数信号。 from:http://www.groad.net/bbs/thread-2621-1-1.html