In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.
Contents |
Callbacks have a wide variety of uses. For example, imagine a function that reads a configuration file and associates values with options. If the options are identified by a hash, then writing the function so that it takes a callback makes it more flexible: the user of it can use whatever hashing algorithm he wishes and the function will continue to work, since it uses the callback to turn option names into hashes; thus, callbacks allow the user of a function to fine-tune it at runtime.
Another use is in error signaling. A Unix program, for example, might not want to terminate immediately when it receives SIGTERM; to make sure things get taken care of, it would register the cleanup function as a callback.
Callbacks may also be used to control whether a function acts or not: Xlib allows custom predicates to be specified to determine whether a program wishes to handle an event.
The following code in C demonstrates the use of callbacks for the specific case of dealing with a POSIX-style signal (in this case SIGUSR1). It should be noted, however, that the use of printf(3) is not safe inside a signal handler.
#include <stdio.h> #include <signal.h> void sig(int signum) { printf("Received signal number %d!\n", signum); } int main(int argc, char *argv[]) { signal(SIGUSR1, sig); while(1); return 0; }
The while loop will keep this example from doing anything interesting, but it will give you plenty of time to send a signal to this process. (If you're on a unix-like system, try a "kill -USR1 <pid>" to the process ID associated with this sample program. No matter how or when you send it, the callback should respond.)
The form of a callback varies among programming languages.
|
|