【发布时间】:2017-04-05 21:16:30
【问题描述】:
我正在编写一个程序,其中 SIGINT 信号在第一次发送时被处理,但之后设置为默认值。所以,例如,我有这个:
static volatile int stop_terminating = 1;
void handler(int dummy) {
stop_terminating = 0;
}
int main(){
signal(SIGINT, handler);
char input[256];
while(1){
if(stop_terminating == 0){
// reset the action of the signal to default
signal(SIGINT, SIG_DFL);
printf("Message sent.\n");
// increment counter so it doesn't enter this condition again
stop_terminating++;
}
printf("User input:\n");
fgets(input, sizeof(input), stdin);
// In this stage, I wanna press CTRL+C and print a message, stopping the fgets
// but what happens is: I press CTRL+C, the signal is catched, but fgets
// is still asking for an input, and after I send something, the my message is printed
// because it looped through the while(1) again.
}
}
如何阻止 fgets 请求输入,只打印消息,然后再次请求输入?
【问题讨论】:
-
volatile不足以进行多线程编程。使用原子。 -
我实际上不知道该怎么做。我一直在努力达到这一点,我只知道部分事情。
-
@Olaf:信号不是线程。
volatile就足够了。 -
@BenVoigt:我想知道为什么
sig_atomic_t会提供额外的保证。有趣的是,这种类型在 C11 的原子支持之前就已经存在了。注意:volatile不保证原子访问。