【发布时间】:2013-10-09 01:42:37
【问题描述】:
我有一个使用 sigaction 设置的信号处理程序,如下所示:
struct sigaction act, oldact;
memset(&act, 0, sizeof(struct sigaction));
act.sa_handler = sig_handler;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGALRM);
sigaddset(&act.sa_mask, SIGINT);
sigaddset(&act.sa_mask, SIGTERM);
sigaddset(&act.sa_mask, SIGTSTP);
sigaction(SIGALRM, &act, &oldact);
sigaction(SIGINT, &act, &oldact);
sigaction(SIGTERM, &act, &oldact);
sigaction(SIGTSTP, &act, &oldact);
act.sa_flags = 0;
在此之后,我运行了一个 for 循环来收集输入并将其打印出来(基本上就像 cat 一样)。
char *linebuf = NULL;
size_t n = 0;
int len;
while(1){
len = getline(&linebuf, &n, stdin);
if(len>0){
printf("%s", linebuf);
}
}
但是,一旦我从处理信号返回,getline() 不再阻塞输入,而是在将errno 设置为EINTR 时始终返回-1,这是一个中断的系统调用。我显然是想打断getline(),但我该如何重置它以便继续阅读输入?
有几个类似的问题并没有真正解决我的问题,但它可能会帮助您更好地理解问题。 12
另一个有趣的消息是,当我使用signal() 进行信号处理时,我没有遇到这个问题,但我改为sigaction(),因为它符合 POSIX。
【问题讨论】:
-
printf(linebuf);可能不是有效的 C 语法。 -
@hacks,是的,应该是
printf("%s", linebuf); -
我已将其更改为
printf("%s", linebuf);但printf(linebuf);是有效的 c 语法(确实给出了此警告warning: format not a string literal and no format arguments [-Wformat-security]但它不是错误),而且不是问题。 -
@ConnorBlanck,这不是错误,但非常危险。想象一下如果
linebuf包含%会发生什么。事实上,如果它包含%n,它可能会被用来覆盖你的记忆,这就是为什么长期以来为Windows编写病毒如此容易的原因。
标签: c signals getline signal-handling