scott
scott

Reputation: 11

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 thought it would print 'beep' until any key has been pressed but the method call is outside the loop? :S

Upvotes: 1

Views: 895

Answers (3)

jilles de wit
jilles de wit

Reputation: 7138

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

Upvotes: 5

kmarsh
kmarsh

Reputation: 1398

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.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881553

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.

Upvotes: 0

Related Questions