~tim/dlopen_test

28cdba33b9196af822fa4190bd7f26e920e69ff2 — Tim Morgan 1 year, 7 months ago
Initial commit
5 files changed, 73 insertions(+), 0 deletions(-)

A .gitignore
A Makefile
A README.md
A lib.c
A main.c
A  => .gitignore +3 -0
@@ 1,3 @@
*.o
*.so*
main

A  => Makefile +6 -0
@@ 1,6 @@
lib: lib.c
	gcc -fPIC -g -c -Wall lib.c
	gcc  lib.o -shared -Wl,-soname,lib.so -o lib.so -lc

main: main.c
	gcc main.c -ldl -o main

A  => README.md +28 -0
@@ 1,28 @@
This sample bit of code demonstrates how to use `dlopen`, `dlsym`, et al to dynamically load
a shared object file into a running process.

1. Compile the library:

   ```
   make lib
   ```

2. Compile the program:

   ```
   make main
   ```

3. Run the program, which will start a loop:

   ```
   ./main
   ```

4. Make a change to the library and recompile:

   ```
   make lib
   ```

5. Witness the output change in the main program.

A  => lib.c +11 -0
@@ 1,11 @@
#include "stdio.h"

void __attribute__ ((constructor)) lib_loaded(void);

void lib_loaded(void) {
  printf("hello from lib_loaded\n");
}

void lib_func(void) {
  printf("hello from lib_func\n");
}

A  => main.c +25 -0
@@ 1,25 @@
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>

int main() {
  while(1) {
    void* lib_handle = dlopen("./lib.so", RTLD_NOW | RTLD_GLOBAL);

    if (lib_handle == NULL) {
      printf("Failed loading lib\n");
    } else {
      printf("Loaded lib successfully\n");

      void (*lib_func)() = dlsym(lib_handle, "lib_func");
      lib_func();

      dlclose(lib_handle);
    }

    sleep(5);
    printf("----------------------------\n");
  }

  return 0;
}