博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nanosleep is better than sleep and usleep
阅读量:2359 次
发布时间:2019-05-10

本文共 3151 字,大约阅读时间需要 10 分钟。

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

转载地址:http://vhntb.baihongyu.com/

你可能感兴趣的文章
朴素的美丽、抑郁中的缕缕阳光——“红衣妹妹”于洋博文选粹
查看>>
最新的计算机方向的国际会议/期刊的排名
查看>>
《蚁群算法原理及其应用》(段海滨)附录Matlab源程序
查看>>
新的探索!
查看>>
小波图像分解与重构程序存在的问题与解决办法
查看>>
小波图像分解 Matlab 程序 - V2.0版
查看>>
小波图像重构 Matlab 程序 - V2.0版
查看>>
投到 ICIC 2008 的蚁群算法论文被录用了,喜忧参半!
查看>>
写科研论文的高级方法学 -- 小木虫上的精华(推荐阅读)
查看>>
Good News -- 投稿到《机器人》的论文也被录用了
查看>>
In this paper 与 In this study 的区别
查看>>
敏捷开发一千零一问系列之三十六:如何做小版本迭代的代码管理
查看>>
敏捷开发产品管理系列之九:划分产品子系统
查看>>
敏捷开发一千零一问系列之三十六:跨平台开发的人员和代码复用
查看>>
关于微软的VB和C#:为何Basic需要存在,为何VB如此像C#,为何两者不合并等
查看>>
度量分析之报告信息的四个层次:数据,信息,分析,措施
查看>>
如何将asp.net MVC2项目升级为MVC3项目(微软官方自动升级工具:ASP.NET MVC 3 Application Upgrader )
查看>>
怎样在Razor中使用HtmlHelper(MvcHtmlString)
查看>>
彼得定律与员工职业生涯规划(该提拔谁,职业规划,知人善用)
查看>>
敏捷开发一千零一问系列之十三:故事点好还是人天好?
查看>>