2

我是Linux编程的新手。我从一本书中复制了以下代码:

#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但它除了 print 什么都不做Hello World!


编辑:Ctrl+C很 抱歉,我已将copy. 很抱歉造成的麻烦。

4

3 回答 3

2

我的建议是不要printf在信号处理程序(ouch)中使用,它可能是未定义的行为。异步信号安全函数: 可以在信号处理程序手册页中调用的安全函数列表

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.

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

于 2013-01-18T13:16:57.477 回答
1

Sorry, I can't see a question here... but I can guess what you are interested in.

printf() is a stateful function, thus not reentrant. It uses a FILE structure (variable name is 'stdin') to keep it's state. (It is like calling fprintf(stdin,format,...)).

That means, dependant on implementation and 'luck', calling printf() from a signal handler may print what you expect, but also may print nothing or may even crash or worse, smash your memory! Anything could happen.

So, just don't call functions from within a signal handler that are not explicitely marked 'signal-safe'. You will avoid lot's of headaches in the long term.

于 2013-01-18T13:50:26.393 回答
0

Put an fflush(stdout) in your signal handler. It was just buffered, then the second SIGINT exited the program before the buffer could be flushed.

于 2013-01-18T13:19:37.160 回答