tags:

views:

212

answers:

3
void main ()
{
  int c;

  signal (SIGINT, Handle);
  while (( c = getchar()) != '\n' );

  return();
}

void Handle(signum) 
{
   signal {SIGINT, Handle); 
   printf ("beep \n");
}

I thought it would print 'beep' until any key has been pressed but the method call is outside the loop? :S

A: 

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.

paxdiablo
+4  A: 

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().

jilles de wit
signal() is deprecated. +1, but please lead the OP to sigaction(), I was going to answer but I'd (mostly) duplicate your answer, beyond suggesting a better method of handling signals.
Tim Post
To answer the (supposed) question I'd add that signal() is re-registered inside "Handle()" - this is why it keeps printing "beep" if you press Ctrl-C repeteadly while in the getchar() loop
Virgil
A: 

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.

kmarsh
I once had to fix a bug that was due to calling `printf` within a signal handler; basically, instead of writing to stdout, the string was being written to an open .mdb file, hosing the database beyond repair. As a rule, signal handlers should not do anything more complicated than setting a flag.
John Bode
The POSIX standard provides a list of functions that shall be async-signal-safe. Therefore, applications can invoke them, without restriction, from signal-catching functions. Here's a link to the POSIX.1-2008 page containing the list http://www.opengroup.org/onlinepubs/9699919799/
jschmier
First of all, the implementations have not caught up to the standards, and second, being safely interruptable is different from being safely callable from inside an interrupt handler. I stand by what I said, for the foreseeable future.
kmarsh