0

Possible Duplicate:
C declaration from standard signal Library

Here is a reference to the link for the syntax. I have only understood the syntax of a pointer to a function. But this is too complex please explain.

http://www.cplusplus.com/reference/clibrary/csignal/signal/

I am trying to understand the precise syntax given( some pointer confusion that I can't resolve ).

Community
  • 1
  • 1
hershey92
  • 783
  • 2
  • 6
  • 17
  • Did you read the [wiki](http://en.wikipedia.org/wiki/C_signal_handling) on signals? – Mike Sep 24 '12 at 17:37
  • Also, please correct your post, the link didn't come through. – Mike Sep 24 '12 at 17:38
  • 1
    Don't get me wrong. I am voting to close & see the dup which is what you asked about :P – P.P Sep 24 '12 at 17:43
  • 2
    See my answer [here](http://stackoverflow.com/questions/9500848/how-do-i-read-this-complex-declaration-in-c/9501054#9501054). – John Bode Sep 24 '12 at 18:00

1 Answers1

4

signal() is pretty easy to understand here's example code from the link I mentioned with my annotations:

//This is a signal handling function. When your main program gets a signal, it
// will call this function. The function just prints a message.
static void catch_function(int signal) {
    printf("Interactive attention signal caught.");
}

int main(void) {
    //register to catch the interrupt signal.
    if (signal(SIGINT, catch_function) == SIG_ERR) {
        printf("An error occurred while setting a signal handler.\n");
        return EXIT_FAILURE;
    }
    while(1)
    {
      printf("do stuff\n");
      sleep(1);
    }
}

Now this code will loop forever (doing something), until it gets a ^C (ctrl+C) interrupt signal. At that point in time it will go do whatever it is we told it to do:

mike@linux-4puc:~> ./a.out 
do stuff
do stuff
^CInteractive attention signal caught.do stuff
do stuff
do stuff
do stuff
do stuff
^CInteractive attention signal caught.do stuff

The signal function is defined as:

typedef void (*sighandler_t)(int); //this just means a pointer to a function
                                   //that looks like:  void sighandler(int)

sighandler_t signal(int signum, sighandler_t handler); 

Which means:

  1. A pointer to a function to handle a signal can be referred to "sighandler_t"
  2. A function that meets the sighandler_t type needs to return nothing, and take an int
  3. The signal function then takes the parameters of the signal type to catch, and a function meeting the "sighandler_t" typedef.

Then at a system level, when our program is running, if a signal comes in and we have handling for it, we do so, if we don't have handling in place, the OS takes a default action.

If you remove the signal call from my above example, you'll see ctrl+C now kills the program instead of just allowing the signal handler to run.

Answer your question?

Mike
  • 47,263
  • 29
  • 113
  • 177