Nowadays , i was reading the APUE.and i found the function defined as below:
void (*signal(int signo, void (*func)(int)))(int);
i was confused,
The general procedure: find the leftmost identifier and work your way out. Absent an explicit grouping with parentheses, postfix operators such as ()
and []
bind before unary operators like *
; thus, the following are all true:
T *x[N] -- x is an N-element array of pointer to T
T (*x)[N] -- x is a pointer to an N-element array of T
T *f() -- f is a function returning a pointer to T
T (*f)() -- f is a pointer to a function returning T
Applying these rules to the declaration, it breaks down as
signal -- signal
signal( ) -- is a function
signal( signo, ) -- with a parameter named signo
signal(int signo, ) -- of type int
signal(int signo, func ) -- and a parameter named func
signal(int signo, *func ) -- of type pointer
signal(int signo, (*func)( )) -- to a function
signal(int signo, (*func)(int)) -- taking an int parameter
signal(int signo, void (*func)(int)) -- and returning void
*signal(int signo, void (*func)(int)) -- returning a pointer
(*signal(int signo, void (*func)(int)))( ) -- to a function
(*signal(int signo, void (*func)(int)))(int) -- taking an int parameter
void (*signal(int signo, void (*func)(int)))(int); -- and returning void
In short, signal
returns a pointer to a function returning void
. signal
takes two parameters: an integer and a pointer to another function returning void
.
You could use typedefs to make this easier to read (and the man page for signal
on Ubuntu linux does just that); however, I think it's valuable to show the non-typedef'd version to demonstrate exactly how the syntax works. The typedef facility is wonderful, but you really need to understand how the underlying types work in order to use it effectively.
The signal
function sets up a signal handler; the second argument is the function that is to be executed if a signal is received. A pointer to the current signal handler (if any) is returned.
For example, if you want your program to handle interrupt signals (such as from Ctrl-C):
static int g_interruptFlag = 0;
void interruptHandler(int sig)
{
g_interruptFlag = 1;
}
int main(void)
{
...
/**
* Install the interrupt handler, saving the previous interrupt handler
*/
void (*oldInterruptHandler)(int) = signal(SIGINT, interruptHandler);
while (!g_interruptFlag)
{
// do something interesting until someone hits Ctrl-C
}
/**
* Restore the previous interrupt handler (not necessary for this particular
* example, but there may be cases where you want to swap out signal handlers
* after handling a specific condition)
*/
signal(SIGINT, oldInterruptHandler);
return 0;
}
EDIT I extended the example code for signal
to something that's hopefully more illustrative.