从信号处理程序的longjmp() [英] longjmp() from signal handler
问题描述
我用下面的code尝试,如果超过5秒后,从用户和超时退出读取输入。这是通过的setjmp / longjmp的和SIGALRM信号的组合来实现的。
I'm using the following code to try to read an input from user and timeout and exit if more than 5 seconds pass. This is accomplished through a combination of setjmp/longjmp and the SIGALRM signal.
这里的code:
#include <stdio.h>
#include <setjmp.h>
#include <unistd.h>
#include <string.h>
#include <sys/signal.h>
jmp_buf buffer;
// this will cause t_gets() to return -2
void timeout() {
longjmp(buffer, 1);
}
int t_gets(char* s, int t)
{
char* ret;
signal(SIGALRM, timeout);
if (setjmp(buffer) != 0)
return -2; // <--- timeout() will jump here
alarm(t);
// if fgets() does not return in t seconds, SIGALARM handler timeout()
// will be called, causing t_gets() to return -2
ret = fgets(s, 100, stdin);
alarm(0);
if (ret == NULL ) return -1;
return strlen(s);
}
int main()
{
char s[100];
int z=t_gets(s, 5);
printf("%d\n", z);
}
现在,我的问题是,如果有什么事,可以去错了这个功能。我读过,与调用longjmp()从信号处理程序有不确定的操作,它到底是什么refferring什么?
Now, my question is if there's anything that can go wrong with this function. I've read that calling longjmp() from a signal handler can have undefined behaviour, what exactly is it refferring to?
另外,如果什么触发报警后立即与fgets()返回,但报警前(0)被称为?它会导致函数返回-2即使用户没有输入的东西吗?
Also, what if the alarm triggers right after fgets() returns, but before alarm(0) is called? Will it cause the function to return -2 even if the user did input something?
在以后编辑:
我不感兴趣的方式来提高code。我只是想知道它如何可能会失败。
LATER I'm not interested in ways to improve the code. I just want to know how it might fail.
推荐答案
从手册页longjmp的:
From the man page for longjmp:
POSIX没有指明是否
的longjmp()
将恢复信号
上下文。如果你想保存和
恢复信号的口罩,使用 siglongjmp()
POSIX does not specify whether
longjmp()
will restore the signal context. If you want to save and restore signal masks, usesiglongjmp()
您的第二个问题:是的,该函数将返回-2,因为的longjmp()
将导致其转到的setjmp(缓冲)
部分,但时间将是非常precise。
Your second question: Yes, the function will return -2 because longjmp()
will cause it to go to the setjmp(buffer)
part, but the timing will have to be very precise.
这篇关于从信号处理程序的longjmp()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!