如何避免scanf函数用C我的信号处理函数后? [英] How to avoid scanf after my signal handler function in C?

查看:222
本文介绍了如何避免scanf函数用C我的信号处理函数后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

#include <stdio.h>
#include <signal.h>
void signal_handler(int signal) {
    printf("Caught signal in CHILD.\n");
}

int main(void) {
    int s;
    signal(SIGTSTP, signal_handler);
    while(1){
         printf("%s@%s/# ",getlogin(),get_current_dir_name());
         scanf("%d",&s);
    }
    return 0;
}

当我运行code它打印:

when i run the code it prints:

something: ^ZCaught signal in CHILD.

据我了解,当我preSS的CTR-Z scanf函数不会执行。虽然我的函数内的printf后,径直向scanf函数,等待输入,然后开始循环again.Is有什么办法避免scanf函数,当我preSS CTR-Z和重新启动while循环?我想类似的东西。

As far i understand that the scanf doesn't execute when i press the ctr-z. Although after the printf inside my function it goes straight to the scanf, waits for input and then starts the loop again.Is there any way to avoid scanf when i press ctr-z and start the while loop again? I tried something like that

void signal_handler(int signal) {
    printf("Caught signal in CHILD.\n");
    printf("%s@%s/# ",getlogin(),get_current_dir_name());
}

但它没有工作。第二个printf去直接scanf函数后,等待输入,然后再开始循环。我可以,不知何故,再次启动循环?

but it didn't work. After the second printf goes straight to the scanf, waits for input and then starts the loop again. Can i, somehow, start the loop again?

推荐答案

信号处理程序的的中断 scanf函数及其阅读。然而,由于你的方式设置信号配置,系统调用立刻在信号处理程序返回重新启动。这就是为什么你在卡在 scanf函数,而不是回到你的循环的顶端。

The signal handler is interrupting scanf during its read of STDIN. However, because of the way you set signal disposition, the read system call restarts immediately upon return of the signal handler. That's why you are "stuck" in the scanf rather than back at the top of your loop.

您可以做一个重要的事情是要使用的sigaction ,而不是信号 。这将迫使你指定中断通话的行为:重新启动与否

One important thing you can do is to use sigaction rather than signal. This will force you to specify the behavior of interrupted calls: restart them or not?

接下来要做的事情就是将信号处理程序限制为那些异步信号安全功能,免得你风险苦难

The next thing to do is to limit your signal handlers to functions that are async-signal-safe, lest you risk misery.

顺便说一句,另一个变化做出是给我们所有的要求包括:(&LT; unistd.h中&GT; )和定义( _GNU_SOURCE ?),让您的工作方案。

As an aside, another change to make is to give us all the required includes (<unistd.h>?) and defines (_GNU_SOURCE ?) to make your program work.

这篇关于如何避免scanf函数用C我的信号处理函数后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆