Question

I have tried to write a signal handling functions in ubuntu. The code is the following:

   #include<signal.h>
   void abc();

   main(){

   printf("Press Ctrl-z key to send SIGINT signal");
   signal(SIGINT,abc);
   for(;;);
   }
   void abc(){
   printf("The key has been pressed");
   }

The intersting factor is: a) First printf() is not shown b) As well as the second printf();

I wrote the code from a book. Can any one pls tell me what mistakes i have made or whether the code will be alterd for ubuntu.

Thanx in advance.

Was it helpful?

Solution

stdout is line buffered.

You might like to append a \n to the strings passed to printf():

printf("The key has been pressed.\n");

If Crtl-C is pressed SIGINT is sent to the process running in foreground. The default handler for SIGINT ends the app.

As the OP's app installs a signal handler for SIGINT which does not end the app, it continues to run if Ctrl-C is pressed and therefore a SIGINT is raised. It is called on Ctl-C as long as it stays installed.

To achieve the behaviour of having abc() called only once, modify the signal handler as follows:

void abc(int sig) /* 'sig' gets the signal nuber passed in (here: 'SIGINT') */
{
  printf("The key has been pressed.\n");
  signal(sig, SIG_DFT); /* (re-)sets the signal handler for `sig` to the default handler. */
}

Further readings: man signal, man sigaction

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top