Advanced Features of Shared Libraries 865
$ LD_LIBRARY_PATH=. ./dynload libdemo.so.1 x1
Called mod1-x1
In the first of the above commands, dlopen() notes that the library path includes a
slash and thus interprets it as a relative pathname (in this case, to a library in the
current working directory). In the second command, we specify a library search
path in LD_LIBRARY_PATH. This search path is interpreted according to the usual rules
of the dynamic linker (in this case, likewise to find the library in the current work-
ing directory).
Listing 42-1: Using the dlopen API
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– shlibs/dynload.c
#include <dlfcn.h>
#include "tlpi_hdr.h"
int
main(int argc, char argv[])
{
void libHandle; / Handle for shared library /
void (funcp)(void); / Pointer to function with no arguments /
const char err;
if (argc != 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s lib-path func-name\n", argv[0]);
/ Load the shared library and get a handle for later use /
libHandle = dlopen(argv[1], RTLD_LAZY);
if (libHandle == NULL)
fatal("dlopen: %s", dlerror());
/ Search library for symbol named in argv[2] /
(void) dlerror(); / Clear dlerror() /
*(void **) (&funcp) = dlsym(libHandle, argv[2]);
err = dlerror();
if (err != NULL)
fatal("dlsym: %s", err);
/ If the address returned by dlsym() is non-NULL, try calling it
as a function that takes no arguments /
if (funcp == NULL)
printf("%s is NULL\n", argv[2]);
else
(*funcp)();
dlclose(libHandle); / Close the library /
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– shlibs/dynload.c