CodeBlanks Logo Icon CodeBlanks

dlclose

Learn to close libraries with dlclose.

What is dlclose?

dlclose closes a handle obtained with dlopen. It decrements the reference count; when it reaches zero, the library is unloaded. The int r = dlclose(h); call returns 0 on success and -1 on error.

Closing prevents resource leaks. If a library has been loaded multiple times with dlopen, you need a dlclose for each call. Continuing to work with a closed handle is unsafe; finish your work first, then close. For testing, printf("closed\n") is enough.

The load-close pattern

The simplest flow: void *h = dlopen(NULL, RTLD_LAZY);, if (h) dlclose(h);, printf("closed\n");. Before calling close, make sure symbol work is finished.

For testing, immediately closing the handle and then printf is enough. The output is deterministic. In real apps, you can check the dlclose return and use dlerror on error. If you use multiple libraries, you must call dlclose for each.

Practice Close the library

Get a handle with void *h = dlopen(NULL, RTLD_LAZY);. Close with if (h) dlclose(h);. Print with printf("closed\n");.

Starter code

main.c
#include <stdio.h>
#include <dlfcn.h>

// Load library
// Close
// Print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <dlfcn.h>

int main(void) {
    void *h = dlopen(NULL, RTLD_LAZY);
    if (h) dlclose(h);
    printf("closed\n");
    return 0;
}

Expected output

closed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 dlclose call

Question
dlclose(____);
Answer
dlclose(h);

Explanation: dlclose closes the h handle.

2 Match dlclose parts

Term Meaning
dlclose Closes handle
0 Success
-1 Error
reference count Counter

3 What does dlclose return on success?

  • void
  • file descriptor
  • 0 or -1 Correct answer
  • void *

Explanation: dlclose returns 0 on success, -1 on error.

All lessons in Advanced