曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 16231|回复: 0
打印 上一主题 下一主题

[常规] nanosleep() -- 更精确的延迟

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 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 组合键,发出中断函数信号。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-4 01:33 , Processed in 0.068199 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表