我为signal handler
创建了alarm()
。父母分叉出另一个没有待处理警报信号的进程。因此,仅在父进程中调用警报。
但是,当调用alarm(2)
时,它会覆盖父进程中的sleep(10)
。父母在打印前只等待2秒钟:
"parent retval=8"
而孩子等了10秒钟。为什么alarm()
信号覆盖sleep()
并且睡眠会返回任何内容(显然它在这种情况下会发生,但是为什么?sleep()
不应该返回任何内容,对吗?)
代码如下。
<headers>
pid_t cpid;
int main() {
int retval;
signal(SIGALRM, handler);
alarm(2);
if ((cpid = fork()) == 0) {
printf(“I’m the child\n”);
retval = sleep(10);
printf(“child retval=%d\n”, retval);
}
else {
printf(“I’m the parent\n”);
retval = sleep(10);
printf(“parent retval=%d\n”, retval);
}
}
/* Handle SIGALRM */
void handler(int sig)
{
if (cpid == 0)
printf(“running child handler\n”);
else
printf(“running parent handler\n”);
}
答案 0 :(得分:1)
如果提前返回,则睡眠返回0或剩余的睡眠秒数。此外,手册页指出混合睡眠和警报是一个坏主意。
NAME
sleep - Sleep for the specified number of seconds
SYNOPSIS
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
DESCRIPTION
sleep() makes the calling process sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
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 handler.
CONFORMING TO
POSIX.1-2001.
BUGS
sleep() may be implemented using SIGALRM; mixing calls to alarm(2) and sleep() is a bad idea.
Using longjmp(3) from a signal handler or modifying the handling of SIGALRM while sleeping will cause undefined results.
SEE ALSO
alarm(2), signal(2), signal(7)
答案 1 :(得分:0)
回归睡眠():
0线程在指定的全部时间内睡眠。
value由于信号的作用是运行信号捕获功能,结束请求或终止进程,因此线程没有全时休眠。返回的值是指定休眠时间内剩余的秒数;也就是说,秒的值减去线程被暂停的实际秒数。
-1 sleep()未成功。设置errno变量以指示错误。
当子项创建时,警报将不会在子进程中继承。