Callback function scenario

November 7, 2017
Programming Tips

Callback Function


Sequential function call the function directly

int compute() {
    // Do something
void main() {
    int result = compute();
    printf("compute result: %d", result);

Callback function is event-driven


  • Step 1: Register the callback function (function pointer and function args as parameters).
  • Step 2: Wait to be called.


Secnario: 如果有 A, B 兩個 programs,希望某個 event 發生的時候 B 可以通知 A
Solution: A 必須傳一個 function pointer 給 B 當 event 發生的時候要執行什麼


a Unix program might not want to terminate immediately when it receives SIGTERM, so to make sure that its termination is handled properly, it would register the cleanup function as a callback.

// Nachos source code
void CallOnUserAbort(void (*func)(int)) {
    (void)signal(SIGTERM, func);
static void Cleanup(int x) {
    cerr << "Cleaning up after signal " << x << "\n";
    delete kernel;
int main() {
    kernel = new Kernel(argc, argv);
    // if user hits Ctrl-C, delete kernel
comments powered by Disqus