views:

13

answers:

1

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

+1  A: 

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);
   : :
paxdiablo
using a general variable? Can you be more specific please?
Mahmoud
Sure thing, @Mahmoud, see my update.
paxdiablo
Even then, the shared variable should either be of type `sig_atomic_t` or you should carefully block signals around critical sections (relative to the mutation of the data shared between the program and the signal handler) as appropriate. See ["Signal Handling"](http://www.gnu.org/s/libc/manual/html_node/Atomic-Data-Access.html#Atomic-Data-Access) in the GNU C library documentation.
Jeremy W. Sherman
+1, but minor nit: make k a sig_atomic_t instead of an int
William Pursell
Thank you so much!
Mahmoud
Also note that it is possible for your program to be signaled before it has a chance to install its signal handler. You are in effect racing the signaler. This is why you should ensure your signal handlers are in place prior to doing anything else.
Jeremy W. Sherman