信号问题,当输入Ctrl + C [英] Signal issue when enter Ctrl+C

查看:167
本文介绍了信号问题,当输入Ctrl + C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux的programming.I新手复制$ C $下面从一本书上C:

I am a newbie in Linux programming.I copied the code below from a book:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void ouch (int sig)
{
    printf("OUCH! - I got signal %d\n", sig);
    (void) signal(SIGINT, SIG_DFL);
}

int main ()
{
    (void) signal(SIGINT, ouch);

    while(1)
    {
        printf("Hello World!\n");
        sleep(1);
    }

}

据预计打印东西时,按Ctrl + C 是entered.But它做什么,但打印的Hello World!

It was expected to print something when Ctrl+C was entered.But it do nothing but print Hello World!.

编辑:
我很抱歉,我已经绑定了按Ctrl + C A快捷键复制
对不起,麻烦引起的。

I am so sorry that I have binded the Ctrl+C as a short-cut key for copy. Sorry for trouble caused.

推荐答案

我的建议是不要使用的printf 在交叉口信号处理器(哎哟的),也可能是不确定的行为。异步信号安全功能:安全名单功能,可以在信号处理程序手册页被调用。

My Suggestion is don't use printf in siginal handler (ouch), it may be undefined behavior. Async-signal-safe functions: The list of safe functions that can be call in signal handler man page.

这不是安全地调用所有功能,如printf,从信号处理程序中。
     一个有用的方法是使用一个信号处理程序设置一个标志,然后检查标志
     从主程序,如果需要打印消息

It is not safe to call all functions, such as printf, from within a signal handler. A useful technique is to use a signal handler to set a flag and then check that flag from the main program and print a message if required.

<子>参考:<一href=\"http://mirror.lzu.edu.cn/docs/ebooks/linux-unix/Linux_EN_Original_Books/%5BLinux%E8%8B%B1%E6%96%87%E5%8E%9F%E7%89%88%E5%9B%BE%E4%B9%A6%E7%B3%BB%E5%88%97%5D.WILEY-Beginning_Linux_Programming_Third_Edition.pdf\"相对=nofollow>开始Linux的编程,第四版,在这本书正是你的code解释,第11章:进程和信号,484页

Reference: Beginning Linux Programming, 4th Edition,In this book exactly your code is explained, Chapter 11: Processes and Signals, page 484

另外一个有用的链接:结果
说明: 使用折返更安全的信号处理函数

An additional helpful link:
Explanation: Use reentrant functions for safer signal handling

这篇关于信号问题,当输入Ctrl + C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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