C语言sleep不起作用

原因如下:

sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

sleep有两种情况会被打破,一是时间已经到了,二是有信号来临

所以sleep提前终止肯定是被什么信号中断的,检查一下再做个应对措施即可。

 

RETURN VALUE Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal han‐ dler. ( 如果定时时间已经过了,sleep返回0,如果sleep被中断,则返回剩余定时时间 )

 

根据sleep的返回值,可以用如下方法实现: