gpt4 book ai didi

c - 处理信号后如何停止从键盘读取?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:31 25 4
gpt4 key购买 nike

我正在编写一个程序,其中 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 请求输入并只打印消息然后再次请求输入?

最佳答案

信号的 Linux 手册页说

Interruption of system calls and library functions by signal handlers

If a signal handler is invoked while a system call or library function call is blocked, then either:

  • the call is automatically restarted after the signal handler returns; or

  • the call fails with the error EINTR.

Which of these two behaviors occurs depends on the interface and whether or not the signal handler was established using the SA_RESTART flag (see sigaction(2)).

您可以将 siginterrupt() 函数与 signal() 一起使用,或者使用 sigaction() 而不是 signal () 用于注册您的信号处理程序,以禁止在信号后重新启动 read() 系统调用。

但是请注意,C 库中的 fgets() 可能会多次调用 read() 直到找到换行符,因此您可能还需要切换到使用较低级别的函数而不是 stdio.h API。

关于c - 处理信号后如何停止从键盘读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241779/

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