Signal problem while typing Ctrl + C

I am new to 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); } } 

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


EDIT: I'm sorry to bind Ctrl+C to the shortcut keys for copy . Sorry for the problem.

+2
source share
3 answers

My suggestion does not use printf in the cigar handler (ouch), it may be undefined behavior. Asynchronous Signal Functions: A list of safe functions that can be called in the signal handler man page .

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

Link: The Beginning of Linux Programming, 4th Edition . This book accurately explains your code, chapter 11: Processes and Signals, page 484

Additional useful link:
Explanation: Use repetitive functions for safer signal processing.

+2
source

Sorry, I donโ€™t see the question here ... but I can guess what interests you.

printf () is a stateful function, so it is not reentrant. It uses the FILE structure (the variable name is "stdin") to save its state. (This is similar to calling fprintf (stdin, format, ...)).

This means that depending on the implementation and โ€œgood luckโ€, calling printf () from the signal handler may print what you expect, but it may also not print anything, or even not crash, or worse, crash the memory! Everything can happen.

So, just do not call functions from the signal handler that are not explicitly marked as "safe for the signal." In the long run, you will avoid a lot of headaches.

+1
source

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

0
source

All Articles