Linux操作系统 sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用

本文详细解释了Linux系统中sleep函数的不同参数用法及其效果,包括sleep(0)、sleep(1)和sleep(-1)的区别,并探讨了这些参数在实际应用中的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用?

sleep(0)、sleep(1)、sleep(-1)的区别,他们各有什么作用?对于Sleep(1)所产生的效果,在不同的系统上会/有不同的表现吗?sleep(-1)的作用是什么?

评论 (4) •   •  链接 •  2012-12-13 
  • 0
    什么地方用的sleep()? –  runer  2012-12-13
  • 0
    man sleep –  斑驳-neo  2012-12-13
  • 0
    @runer linux,多线程 –  freeboy1015  2012-12-14
  • 0
    还没用过sleep(-1) –  274131487  2012-12-18
3个答案

linux中sleep的函数参数是unsigned int,如下:

       
  1. #include <unistd.h>
  2. unsigned int sleep(unsigned int seconds);

参考链接:sleep(3) - Linux man page

sleep(-1)调用导致隐形的类型转换,-1就转化成0xffffffff,也就是32位无符号整形的最大值

sleep(0)的结果与系统实现有关, glibc针对Linux的实现, sleep(0)不会做任何系统调用而直接返回。(glibc2.9中sleep源码)

       
  1. /* We are going to use the `nanosleep' syscall of the kernel.  
  2.    But the kernel does not implement the stupid SysV SIGCHLD
  3.    vs. SIG_IGN behaviour for this syscall.  Therefore we have
  4.    to emulate it here.  */
  5. unsigned int
  6. __sleep (unsigned int seconds)
  7. {
  8.   const unsigned int max
  9.     = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1);
  10.   struct timespec ts;
  11.   sigset_t set, oset;
  12.   /* This is not necessary but some buggy programs depend on this.  */
  13.   if (__builtin_expect (seconds == 0, 0))
  14.     {
  15. #ifdef CANCELLATION_P
  16.       CANCELLATION_P (THREAD_SELF);  //相当于 pthread_testcancel();0
  17. #endif
  18.       return 0;
  19.     }
  20. ... ...
  21. }

只有sleep(1)时, 才会调用到nanosleep

参考链接:
关于sleep(0)
sched_yield vs. sleep(0)

freeboy1015
freeboy1015
2598
编辑于  2012-12-17
评论 (1) •  链接 • 2012-12-17
  • 0
    我看的一段代码中sleep(-1)的功能好像是“阻止程序退出”。 –  freeboy1015  2012-12-17

sleep(-1)就是sleep(UINT_MAX)

评论 (0) •  链接 • 2012-12-13

sleep(0)是让出CPU
linux下是usleep吧

评论 (0) •  链接 • 2012-12-17
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值