unistd.h 中 `sleep` 和 `pause` 库函数的区别
Difference between `sleep` and `pause` library functions in unistd.h
来自 pause
的手册页
pause() causes the calling process (or thread) to sleep until a signal is delivered that either terminates the process or causes the invocation of a signal-catching function.
来自 sleep
的手册页
sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
/* This will wait till the signal arrives and it should be handled */
pause();
/* is it same as the above one */
/* This will also sleep for infinite time untill the signal arrives and it should be handled */
while (1) {
int ret = sleep(3);
if (ret != 0)
break;
}
sleep
and pause
的源代码,两者的实现方式不同。
它们的实现方式有什么区别?
从应用程序的角度来看,何时使用 pause
以及何时使用 sleep
.
两者都可以通过以下方式在 POSIX 系统上轻松实现:
#include <poll.h>
int pause(){ return poll(0, 0, -1); }
int sleep(unsigned int s){ return poll(0, 0, s * 1000); }
事实上,第二个是作弊,因为sleep
应该return如果被打扰还有时间睡觉,但谁真正关心那个\;-.
但这正是 sleep(3)
在 glibc 源代码中以更 round-about 的方式实现的原因。否则,任何阻塞 non-restartable 系统调用都可以,包括但不限于 nanosleep(2)
、poll(2)
、select(2)
或 sigsuspend(2)
。用什么更多是兼容性问题
sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
所以 pause
完全阻止线程的执行,直到收到信号,但是 sleep
有第二种可能性来解除线程的阻塞,即指定等待的秒数。因此,使用 pause
你必须等待信号到达,但使用睡眠,你有可能只等待特定时间,就像在网络中你不会无限等待包到达(超时)。
来自 pause
pause() causes the calling process (or thread) to sleep until a signal is delivered that either terminates the process or causes the invocation of a signal-catching function.
来自 sleep
sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
/* This will wait till the signal arrives and it should be handled */
pause();
/* is it same as the above one */
/* This will also sleep for infinite time untill the signal arrives and it should be handled */
while (1) {
int ret = sleep(3);
if (ret != 0)
break;
}
sleep
and pause
的源代码,两者的实现方式不同。
它们的实现方式有什么区别?
从应用程序的角度来看,何时使用 pause
以及何时使用 sleep
.
两者都可以通过以下方式在 POSIX 系统上轻松实现:
#include <poll.h>
int pause(){ return poll(0, 0, -1); }
int sleep(unsigned int s){ return poll(0, 0, s * 1000); }
事实上,第二个是作弊,因为sleep
应该return如果被打扰还有时间睡觉,但谁真正关心那个\;-.
但这正是 sleep(3)
在 glibc 源代码中以更 round-about 的方式实现的原因。否则,任何阻塞 non-restartable 系统调用都可以,包括但不限于 nanosleep(2)
、poll(2)
、select(2)
或 sigsuspend(2)
。用什么更多是兼容性问题
sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
所以 pause
完全阻止线程的执行,直到收到信号,但是 sleep
有第二种可能性来解除线程的阻塞,即指定等待的秒数。因此,使用 pause
你必须等待信号到达,但使用睡眠,你有可能只等待特定时间,就像在网络中你不会无限等待包到达(超时)。