mabounassif
mabounassif

Reputation: 2341

Keyboard signal handling, adding parameters to callback handler function (Ubuntu, intel)

I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void
signal_callback_handler(int signum)
{
   printf("Caught signal %d\n",signum);
   // Cleanup and close up stuff here

   // Terminate program
   exit(signum);
}

int main()
{
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);

   while(1)
   {
      printf("Program processing stuff here.\n");
      sleep(1);
   }
   return EXIT_SUCCESS;
}

Is there a way to pass an extra argument in the callback function? Something like:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void
signal_callback_handler(int signum, int k)
{

   k++; // Changing value of k
}

int main()
{
   int k = 0;
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler(k);

   while(1)
   {
      printf("Program processing stuff here.\n");
      printf(" blah %d\n", k);
      sleep(1);
   }
   return EXIT_SUCCESS;
}

Thank you

Upvotes: 0

Views: 3962

Answers (1)

paxdiablo
paxdiablo

Reputation: 881093

No, there's not, and there's very little that you should actually be doing in a signal handler anyway.

I generally just set a flag and return, letting the real code handle it from then on.

If you really wanted to do that, you could make k a file-level static so that both main and the signal handler (and every other function in the file) could access it, but you might want to investigate the safety of that option (whether a signal handler can run while the real program is using or updating the value).

In other words, something like:

static int k = 0;

void signal_callback_handler(int signum) {
   k++; // Changing value of k
}

int main() {
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);
   : :

Upvotes: 2

Related Questions