1

I am quite new to C and I can not successfully understand the following code:

#include <signal.h> //1
typedef void (*sighandler_t)(int); //2
sighandler_t signal (int signo, sighandler_t handler); //3

Line 3 is:

signal is a function that takes 2 arguments, one being an integer and the other being a sighandler_t and returns a sighandler_t?

But what is sighandler_t?

Is it a pointer to a function, where the function that is being pointed is a function that takes an argument of type int and returns void?

Can you give an example on how I can use it?

9
  • 1
    signal() is depreciated these days. "man signal" says: The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use:use sigaction(2) instead. Commented Jun 4, 2015 at 20:55
  • 6
    @StarPilot It does, since 16 years ago. Commented Jun 4, 2015 at 20:56
  • gcc (at least) recognizes C++ style comments. It is C. Commented Jun 4, 2015 at 20:57
  • If you plan to use function pointers in C consider using raw pointers instead. Commented Jun 4, 2015 at 20:57
  • @AlexandreSeverino This is from a book really. Linux System Programming. What do you mean use raw pointers? Commented Jun 4, 2015 at 20:58

1 Answer 1

3

Line

typedef void (*sighandler_t)(int);  

define a new type sighandler_t which is pointer to a function which expects an argument of type int and returns nothing.

Line

sighandler_t signal (int signo, sighandler_t handler);  

declares signal a function which expects its first argument of type int and second argument of type sighandler_t and returns a type sighandler_t.
sighandler_t is user defined type which is ultimately pointer to a function which expects an argument of type int and returns nothing.

Without typedef it would be written as

void (*signal(int signo, void (*handler)(int)))(int);  

which is more confusing.

Sign up to request clarification or add additional context in comments.

6 Comments

I am still confused. Is sighandler_t defined in standard C, or is it just the book I am reading?
Why would ´signal´ return a ´pointer to a function´ ?
Thanks for the great answer, the only thing I do not understand is, how is the return value of signal useful?
The return value may be used to call a function of type sighandler_t.
so like handle a signal, and then run a different function?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.