Help with implementing signal handlers via signal()
void main ()
{
int c;
signal (SIGINT, Handle);
while (( c = getchar()) != '\n' );
return();
}
void Handle(signum)
{
signal {SIGINT, Handle);
printf ("beep \n");
}
I th开发者_开发知识库ought it would print 'beep' until any key has been pressed but the method call is outside the loop? :S
You register Handle() as handler for SIGINT. Signal SIGINT is sent when the user tries to interrupt the program, so if you start this program it should print beep if you press control-c.
See some documentation about SIGINT, about the signal() function and about using it.
As Tim points out below, use sigaction() instead of signal().
Handle
is only called when an INT signal is delivered to the code (most likely when you press CTRLC or CTRLBREAK although there are other ways to raise that signal), not continuously while waiting for a keypress.
You'll also find that the lines
signal {SIGINT, Handle);
and
return();
are typos - that first brace should be a parenthesis and you should use return 0;
for the second. In addition, main
should return an integer if you want to be standards-compliant.
Besides using sigaction...
Please change the callback to NOT call printf. Printf calls system call write() and writes to the standard out buffer, mixing with the main's calls. Both system calls and modifying stdout should be avoided in a signal handler.
Instead, set a sig_atomic_t flag variable in the signal handler, and then check and unset it and do the printf in the main loop.
精彩评论