gpt4 book ai didi

c Alarm() 和pause() 导致永远暂停

转载 作者:行者123 更新时间:2023-12-03 03:30:46 26 4
gpt4 key购买 nike

在下面的程序中,暂停被中断一次,但随后暂停再也没有返回。我已设置闹钟来中断暂停,所以我很困惑为什么暂停永远不会返回?

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

static void sig_alrm(int);
static jmp_buf env_alrm;


int main(int arc, char **argv)
{

int x;
x = setjmp(env_alrm);
printf("setjmp was created with return value: %d\n", x);

if(signal(SIGALRM, sig_alrm) == SIG_ERR)
{
printf("Error settting SIGALRM\n");
exit(1);
}


if((x!= 0) && (x!=1))
{

printf("Error setting setjmp\n");
exit(1);
}

printf("Line next to setjmp\n");
x = alarm(2);
printf("Alarm set for 2 seconds, remaning secs from previous alarm: %d\n");
pause();
printf("Line next to pause()\n");
alarm(0);
return 0;
}

static void sig_alrm(int signo)
{
longjmp(env_alrm, 1);
}

这是输出,最后一行显示应用程序暂停的位置

setjmp was created with return value: 0
Line next to setjmp
Alarm set for 2 seconds, remaining secs from previous alarm: 0
setjmp was created with return value: 1
Line next to setjmp
Alarm set for 2 seconds, remaining secs from previous alarm: 0

最佳答案

使用 sigsetjmp()siglongjmp() 来保存和恢复信号掩码(Linux 默认情况下不保存信号掩码),以清除任何待处理的信号,来自男人setjmp() :

POSIX does not specify whether setjmp() will save the signal mask. In System V it will not.By default, Linux/glibc follows the System V behavior. If you want to portably save and restore signal masks, use sigsetjmp() and siglongjmp().

注意:我不确定您想要完成什么,但您的代码看起来应该在无限循环中运行,调用 longjmp() 恢复执行,就好像它刚刚执行一样从 setjmp() 返回并永远持续下去。

关于c Alarm() 和pause() 导致永远暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com