sleep(0)、sleep(1)和sleep(-1)的区别,他们各有什么作用?
3个答案
linux中sleep的函数参数是unsigned int,如下:
参考链接:sleep(3) - Linux man page
sleep(-1)调用导致隐形的类型转换,-1就转化成0xffffffff,也就是32位无符号整形的最大值。
sleep(0)的结果与系统实现有关, glibc针对Linux的实现, sleep(0)不会做任何系统调用而直接返回。(glibc2.9中sleep源码)
- /* We are going to use the `nanosleep' syscall of the kernel.
- But the kernel does not implement the stupid SysV SIGCHLD
- vs. SIG_IGN behaviour for this syscall. Therefore we have
- to emulate it here. */
- unsigned int
- __sleep (unsigned int seconds)
- {
- const unsigned int max
- = (unsigned int) (((unsigned long int) (~((time_t) 0))) >> 1);
- struct timespec ts;
- sigset_t set, oset;
- /* This is not necessary but some buggy programs depend on this. */
- if (__builtin_expect (seconds == 0, 0))
- {
- #ifdef CANCELLATION_P
- CANCELLATION_P (THREAD_SELF); //相当于 pthread_testcancel();0
- #endif
- return 0;
- }
-
- ... ...
-
- }
只有sleep(1)时, 才会调用到nanosleep。