C语言的sleep、usleep、nanosleep等休眠函数如何使用

这篇文章主要讲解了“C语言的sleep、usleep、nanosleep等休眠函数如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C语言的sleep、usleep、nanosleep等休眠函数如何使用”吧!

引子

一个无聊的死循环小代码:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    for (char c = 0; c < 128; c++) {
                printf("cool\n");
    }
    return 0;
}

以及 运行过程 展示版:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    struct timespec n_sleep;
    n_sleep.tv_sec = 0; //secondes, integer part sleep duration
    n_sleep.tv_nsec = 5e8L; //nanoseconds, decimal part sleep duration

    char c;
    for (c = 0; c < 128; c++) {
        printf("char of c :%c\n", c);
        printf("ASCII num of c :%d\n", c);
        sleep(1); // 1 s
        usleep(900000); // 0.9 s 
        nanosleep(&n_sleep, NULL); // 0 + 0.5 s
    }
    return 0;
}

另外,推荐一下 clang 这款编译器,
它的(1)错误、(2)警告 提示非常直观、准确、体贴。
比如,上面的死循环代码,编译之后,它就贴心地显示了一个警告:

result of comparison of constant 128 with expression of type 'char' is always true
      [-Wtautological-constant-out-of-range-compare]
              for (c = 0; c < 128; c++) {
                        ~ ^ ~~~

强烈推荐啊!!!
当然,如果还是喜欢或者必须使用 gcc 的话,建议可以将 clang 作为一个辅助选项。

(一) sleep 函数

头文件 unistd.h
头文件 unistd.h 中的原文如下:

/* Make the process sleep for SECONDS seconds, or until a signal arrives
   and is not ignored.  The function returns the number of seconds less
   than SECONDS which it actually slept (thus zero if it slept the full time).
   If a signal handler does a `longjmp' or modifies the handling of the
   SIGALRM signal while inside `sleep' call, the handling of the SIGALRM
   signal afterwards is undefined.  There is no return value to indicate
   error, but if `sleep' returns SECONDS, it probably didn't work.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern unsigned int sleep (unsigned int __seconds);

通过debug的方式,进入 sleep 函数本体内部,可以反向查找到 sleep 函数所在的具体文件是 /glibc-2.23/sysdeps/posix/sleep.c 。

(根据gcc版本的不同,上面的库函数版本号 glibc-2.23 有所不同。)

源文件 sleep.c

sleep 函数的原型代码如下:

#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <sys/param.h>

/* Make the process sleep for SECONDS seconds, or until a signal arrives
   and is not ignored.  The function returns the number of seconds less
   than SECONDS which it actually slept (zero if it slept the full time).
   If a signal handler does a `longjmp' or modifies the handling of the
   SIGALRM signal while inside `sleep' call, the handling of the SIGALRM
   signal afterwards is undefined.  There is no return value to indicate
   error, but if `sleep' returns SECONDS, it probably didn't work.  */
unsigned int __sleep(unsigned int seconds)
{
    int save_errno = errno;

    const unsigned int max =
        (unsigned int)(((unsigned long int)(~((time_t)0))) >> 1);
    struct timespec ts = { 0, 0 };
    do {
        if (sizeof(ts.tv_sec) <= sizeof(seconds)) {
            /* Since SECONDS is unsigned assigning the value to .tv_sec can
             overflow it.  In this case we have to wait in steps.  */
            ts.tv_sec += MIN(seconds, max);
            seconds -= (unsigned int)ts.tv_sec;
        } else {
            ts.tv_sec = (time_t)seconds;
            seconds = 0;
        }

        if (__nanosleep(&ts, &ts) < 0)
            /* We were interrupted.
           Return the number of (whole) seconds we have not yet slept.  */
            return seconds + ts.tv_sec;
    } while (seconds > 0);

    __set_errno(save_errno);

    return 0;
}
weak_alias(__sleep, sleep)

sleep 函数的用法

简单地说, sleep 函数实现的功能是 让程序休眠若干秒钟,时间的最小刻度是「秒」。

extern unsigned int sleep (unsigned int __seconds);

sleep 函数的返回值

  • (1)如果 sleep 函数顺利执行了的话,返回值是实际休眠的时间数,

  • (2)如果实际休眠的时间和设定的休眠时间一致的话,返回值是0,

  • (3)不会返回表示 错误 信息的值,但是如果返回的值与设定的休眠时间的值一样的话,很可能 sleep 函数其实并没有执行,

  • (4)返回值类型是 unsigned int 型,也就是说,是一个 非负数 。

sleep 函数的参数

  • (1)参数的类型是 unsigned int 型,也就是说,是一个 非负数 ,

  • (2)参数的时间单位是 秒 。

所以, sleep 函数,使 进程/process 休眠的最短时间段,是一秒钟。

(二) usleep 函数

头文件 unistd.h
头文件 unistd.h 中的原文如下:

/* Sleep USECONDS microseconds, or until a signal arrives that is not blocked
   or ignored.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int usleep (__useconds_t __useconds);

查找上面的 sleep.c 文件的时候,在 find 命令的结果中看到了 usleep.c 文件和 sleep.c 文件位于同一个文件夹:
/glibc-2.23/sysdeps/posix/sleep.c 。

(根据gcc版本的不同,上面的库函数版本号 glibc-2.23 有所不同。)

源文件 usleep.c

usleep 函数的原型代码如下:

#include <time.h>
#include <unistd.h>

int
usleep (useconds_t useconds)
{
  struct timespec ts = { .tv_sec = (long int) (useconds / 1000000),
             .tv_nsec = (long int) (useconds % 1000000) * 1000ul };

  /* Note the usleep() is a cancellation point.  But since we call
     nanosleep() which itself is a cancellation point we do not have
     to do anything here.  */
  return __nanosleep (&ts, NULL);
}

名称 usleep 的第一个字母 u 代表的是时间单位 微秒 的第一个字母。
虽然实际上是希腊字母的 &mu; ,但英语键盘里不方便敲出这个字母,所以就用了样子相似的英文字母 u 。
时间单位 微秒 的英文单词是 microsecond ,是由词根 micro 和 second 组合而成的单词。
微秒 是 10的负6次方 秒。

另外,还有一个以字母 m 开头的时间单位的英文单词 millisecond ,意思是 毫秒 ,也就是 千分之一秒。
注意,区分 micro 和 milli ,一个是 微 ,一个是 毫 。

usleep 函数的用法

简单地说, usleep 函数实现的功能是 让程序休眠若干「微秒」,时间的最小刻度是「微秒」,10的负6次方 秒。

/* Sleep USECONDS microseconds, or until a signal arrives that is not blocked
   or ignored.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int usleep (__useconds_t __useconds);

usleep 函数的返回值

网上查到的是:成功返回0,出错返回-1。

usleep 函数的参数

  • (1) 参数的类型是 __useconds_t ,这个类型的定义要查找好几个文件才找得到,

  • (2) 首先是找到了头文件 types.h ,具体路径是 /glibc/include/sys/types.h ,可惜这里面没有明确、具体的定义,

  • (3) 然后还得找到头文件 typesizes.h ,具体路径是 ==/glibc/sysdeps/mach/hurd/bits/typesizes.h ==,这里终于有了,

  • (4) 第一个宏, #define __USECONDS_T_TYPE __U32_TYPE ,在 typesizes.h 文件里,

  • (5) 第二个宏, #define __U32_TYPE unsigned int ,在 types.h 文件里,

  • (6) 真是折腾啊!这下总算知道 __useconds_t 就是 unsigned int 类型了,也就是 非负整数。

  • (7) 参数的时间单位是 微秒 。

所以, usleep 函数,使 进程/process 休眠的最短时间段,是一微秒。

(三) nanosleep 函数

头文件 time.h
这个 time.h 头文件的路径是 /glibc/time/time.h 。
在C语言自带的库目录里面,有好几个不同目录下的 time.h 文件,只有这个才是定义了 nanosleep 函数的。
也不知道,编译器在预处理阶段去获取的 time.h 到底是哪个? 或者说,全部都获取过来了?

头文件 time.h 中的原文如下:

/* Pause execution for a number of nanoseconds.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int nanosleep (const struct timespec *__requested_time,
              struct timespec *__remaining);

函数名称的 nano 是 纳米、纳秒 等计量单位的开头字母,一纳秒是10的负9次方 秒,是10的负6次方 毫秒,是10的负3次方 微秒。

源文件 nanosleep.c

下面是这个路径 /glibc/posix/nanosleep.c 的文件内容。

在C语言自带的函数库中搜索 nanosleep ,出来的结果同样有好几个,暂时分不清到底是哪个,先采用了这个。

nanosleep 函数的原型代码如下:

#include <errno.h>
#include <time.h>


/* Pause execution for a number of nanoseconds.  */
int
__nanosleep (const struct timespec *requested_time,
         struct timespec *remaining)
{
  __set_errno (ENOSYS);
  return -1;
}
stub_warning (nanosleep)

hidden_def (__nanosleep)
weak_alias (__nanosleep, nanosleep)

nanosleep 函数的用法

简单地说, nanosleep 函数实现的功能是 让程序休眠若干「纳秒」,时间的最小刻度是「纳秒」,10的负9次方 秒。

/* Pause execution for a number of nanoseconds.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int nanosleep (const struct timespec *__requested_time,
              struct timespec *__remaining);

nanosleep 函数的返回值

网上查到的是:成功返回0,出错返回-1。

这个函数功能是暂停某个进程直到你规定的时间后恢复,参数 req 就是你要暂停的时间,其中 req->tv_sec 是以秒为单位,而 tv_nsec 以纳秒为单位(10的-9次方秒)。

由于调用 nanosleep 是进程进入 TASK_INTERRUPTIBLE ,这种状态是会相应信号而进入 TASK_RUNNING 状态的,这就意味着有可能会没有等到你规定的时间就因为其它信号而唤醒,此时函数返回 -1 ,切换剩余的时间会被记录在 rem 中。

return值: 若进程暂停到参数 *req 所指定的时间,成功则返回0;若有信号中断则返回-1,并且将剩余微秒数记录在 *rem 中。

nanosleep 函数的参数

第一个参数 *__requested_time 的数据类型是 struct timespec ,定义在 time.h 文件中,

具体是定义在 /glibc/time/bits/types/struct_timespec.h 文件中的。
文件内容如下:

#include <bits/types.h>

/* POSIX.1b structure for a time value.  This is like a `struct timeval' but
   has nanoseconds instead of microseconds.  */
struct timespec
{
  __time_t tv_sec;        /* Seconds.  */
  __syscall_slong_t tv_nsec;    /* Nanoseconds.  */
};

对于 struct timespec 数据类型的详细说明如下:
(昨天晚上上网查资料、自行测试的时候,自己写的英文笔记,请忽略语法疏漏~)

in header file of C lib, time.h, declaration as below:

struct timespec; (since C11)

struct timespec {
    time_t tv_sec; // seconds
    long tv_nsec; // nanoseconds
};

Member objects / 结构体成员:

time_t tv_sec whole seconds (valid values are >= 0)
long tv_nsec nanoseconds (valid values are [0, 999999999])

time_t 类型是 long 型,成员 tv_sec 决定 休眠持续时间段的 整数部分:

member of 「tv_sec」 at the type of 「time_t」,
aka (also know as) 「long」 type,
determines the integer part of sleep duration;

time_t 类型是 long 型,成员 tv_nsec 决定 休眠持续时间段的 小数部分:

member of 「tv_nsec」 at the type of 「long」,
and in the range of [0, 999999999] or [0,1e9),
that means tv_nsec is forever less than 1 second,
determines the decimal part of sleep duration.

就算赋值给成员 tv_nsec 的数值直接计算下来超过了一秒,成员 tv_nsec 获得的实际的值也是被取余后的结果。

even if a value more than 999999999 ns given to tv_nsec,
actually what tv_nsec will get is a value cut down extra part,
eg. 1e9L or 100000000 will be cut the high bits and leave 0 to tv_nsec.

总而言之,整个的休眠时间段是 整数部分的 tv_sec 加上 小数部分的 tv_nsec 组成的。

so, the whole sleep duration is tv_sec + tv_nsec,
just as 「integer part + decimal part」 of the whole sleep duration.

所以, nanosleep 函数,使 进程/process 休眠的最短时间段,是一纳秒。

注意

  • unistd.h 是 unix 系统标准头文件,用于系统调用,相当于 win32 中的 windows.h , unistd.h 定义的函数只能用于 UNIX 环境中,而不能用于 windows 。

  • 所以 sleep 和 usleep 只能用于 Linux / Unix 下,而不能用于 windows 。

  • nalosleep 和 其它时间日期操作函数 一样,都是定义在 time.h 中的,所以都适用。

  • 使用 clang 编译c程序文件的时候,提示「警告」说, usleep 和 nanosleep 在 C99 中是非法的。不过因为实际采用的是 C11 标准,所以还是编译通过了,也能正常执行。这里只是 clang 的一个善意的提醒吧。

感谢各位的阅读,以上就是“C语言的sleep、usleep、nanosleep等休眠函数如何使用”的内容了,经过本文的学习后,相信大家对C语言的sleep、usleep、nanosleep等休眠函数如何使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


一.C语言中的static关键字 在C语言中,static可以用来修饰局部变量,全局变量以及函数。在不同的情况下static的作用不尽相同。 (1)修饰局部变量 一般情况下,对于局部变量是存放在栈区的,并且局部变量的生命周期在该语句块执行结束时便结束了。但是如果用static进行修饰的话,该变量便存
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针和数组的一些区别,然而在某些情况下,指针和数组是等同的,下面讨论一下什么时候指针和数组是相同的。C语言标准对此作了说明:规则1:表达式中的数组名被编译器当做一个指向该数组第一个元素的指针; 注:下面几种情况例外 1)数组名作为sizeof的操作数
浅谈C/C++中的指针和数组(一)指针是C/C++的精华,而指针和数组又是一对欢喜冤家,很多时候我们并不能很好的区分指针和数组,对于刚毕业的计算机系的本科生很少有人能够熟练掌握指针以及数组的用法和区别。造成这种原因可能跟现在大学教学以及现在市面上流行的很多C或者C++教程有关,这些教程虽然通俗易懂,
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时,书中谈到C语言的声明问题,《C专家编程》这本书只有两百多页,却花了一章的内容去阐述这个问题,足以看出这个问题的重要性,要想透彻理解C语言的声明问题仅仅看书是远远不够的,需要平时多实践并大量阅读别人写的代码。下面借鉴《C专家编程》书中的两个
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下与文件相关的东西。一.文本文件和二进制文件 文本文件的定义:由若干行字符构成的计算机文件,存在于计算机系统中。文本文件只能存储文件中的有效字符信息,不能存储图像、声音等信息。狭义上的二进制文件则指除开文本文件之外的文件,如图片、DOC文档。
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面说一下文件的读写操作。文件的读写操作主要有4种,字符读写、字符串读写、块读写以及格式化读写。一.字符读写 字符读写主要使用两个函数fputc和fgetc,两个函数的原型是: int fputc(int ch,FILE *fp);若写入成功则
浅谈C语言中的位段 位段(bit-field)是以位为单位来定义结构体(或联合体)中的成员变量所占的空间。含有位段的结构体(联合体)称为位段结构。采用位段结构既能够节省空间,又方便于操作。 位段的定义格式为: type [var]:digits 其中type只能为int,unsigned int,s
C语言文件操作解析(五)之EOF解析 在C语言中,有个符号大家都应该很熟悉,那就是EOF(End of File),即文件结束符。但是很多时候对这个理解并不是很清楚,导致在写代码的时候经常出错,特别是在判断文件是否到达文件末尾时,常常出错。1.EOF是什么? 在VC中查看EOF的定义可知: #def
关于VC+ʶ.0中getline函数的一个bug 最近在调试程序时,发现getline函数在VC+ʶ.0和其他编译器上运行结果不一样,比如有如下这段程序:#include &lt;iostream&gt;#include &lt;string&gt;using namespace std;int
C/C++浮点数在内存中的存储方式 任何数据在内存中都是以二进制的形式存储的,例如一个short型数据1156,其二进制表示形式为00000100 10000100。则在Intel CPU架构的系统中,存放方式为 10000100(低地址单元) 00000100(高地址单元),因为Intel CPU
浅析C/C++中的switch/case陷阱 先看下面一段代码: 文件main.cpp#includeusing namespace std;int main(int argc, char *argv[]){ int a =0; switch(a) { case ...
浅谈C/C++中的typedef和#define 在C/C++中,我们平时写程序可能经常会用到typedef关键字和#define宏定义命令,在某些情况下使用它们会达到相同的效果,但是它们是有实质性的区别,一个是C/C++的关键字,一个是C/C++的宏定义命令,typedef用来为一个已有的数据类型
看下面一道面试题:#include&lt;stdio.h&gt;#include&lt;stdlib.h&gt;int main(void) { int a[5]={1,2,3,4,5}; int *ptr=(int *)(&amp;aʱ); printf(&quot;%d,%d&quot;,*(
联合体union 当多个数据需要共享内存或者多个数据每次只取其一时,可以利用联合体(union)。在C Programming Language 一书中对于联合体是这么描述的: 1)联合体是一个结构; 2)它的所有成员相对于基地址的偏移量都为0; 3)此结构空间要大到足够容纳最&quot;宽&quo
从一个程序的Bug解析C语言的类型转换 先看下面一段程序,这段程序摘自《C 专家编程》:#include&lt;stdio.h&gt;int array[]={23,34,12,17,204,99,16};#define TOTAL_ELEMENTS (sizeof(array)/sizeof(ar
大端和小端 嵌入式开发者应该对大端和小端很熟悉。在内存单元中数据是以字节为存储单位的,对于多字节数据,在小端模式中,低字节数据存放在低地址单元,而在大端模式中,低字节数据存放在高地址单元。比如一个定义一个short型的变量a,赋值为1,由于short型数据占2字节。在小端模式中,其存放方式为0X40
位运算和sizeof运算符 C语言中提供了一些运算符可以直接操作整数的位,称为位运算,因此位运算中的操作数都必须是整型的。位运算的效率是比较高的,而且位运算运用好的话会达到意想不到的效果。位运算主要有6种:与(&amp;),或(|),取反(~),异或(^),左移(&gt;)。1.位运算中的类型转换位
C语言文件操作解析(四)在文件操作中除了打开操作以及读写操作,还有几种比较常见的操作。下面介绍一下这些操作中涉及到的函数。一.移动位置指针的函数 rewind函数和fseek函数,这两个函数的原型是:void rewind(FILE *fp); 将位置指针移动到文件首 int fseek(FILE
结构体字节对齐 在用sizeof运算符求算某结构体所占空间时,并不是简单地将结构体中所有元素各自占的空间相加,这里涉及到内存字节对齐的问题。从理论上讲,对于任何变量的访问都可以从任何地址开始访问,但是事实上不是如此,实际上访问特定类型的变量只能在特定的地址访问,这就需要各个变量在空间上按一定的规则排
C语言文件操作解析(二)C语言中对文件进行操作必须首先打开文件,打开文件主要涉及到fopen函数。fopen函数的原型为 FILE* fopen(const char *path,const char *mode) 其中path为文件路径,mode为打开方式 1)对于文件路径,只需注意若未明确给出绝