1 #include <dlfcn.h>
2 #include <elf.h>
3 #include <errno.h>
4 #include <error.h>
5 #include <link.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 
9 #define MAPS ((struct link_map *) _r_debug.r_map)
10 
11 #define OUT \
12   for (map = MAPS; map != NULL; map = map->l_next)			      \
13     if (map->l_type == lt_loaded)					      \
14       printf ("name = \"%s\", direct_opencount = %d\n",			      \
15 	      map->l_name, (int) map->l_direct_opencount);		      \
16   fflush (stdout)
17 
18 int
main(void)19 main (void)
20 {
21   void *h[3];
22   struct link_map *map;
23   void (*fp) (void);
24 
25   h[0] = dlopen ("unload2mod.so", RTLD_LAZY);
26   h[1] = dlopen ("unload2mod.so", RTLD_LAZY);
27   if (h[0] == NULL || h[1] == NULL)
28     error (EXIT_FAILURE, errno, "cannot load \"unload2mod.so\"");
29   h[2] = dlopen ("unload2dep.so", RTLD_LAZY);
30   if (h[2] == NULL)
31     error (EXIT_FAILURE, errno, "cannot load \"unload2dep.so\"");
32 
33   puts ("\nAfter loading everything:");
34   OUT;
35 
36   dlclose (h[0]);
37 
38   puts ("\nAfter unloading \"unload2mod.so\" once:");
39   OUT;
40 
41   dlclose (h[1]);
42 
43   puts ("\nAfter unloading \"unload2mod.so\" twice:");
44   OUT;
45 
46   fp = dlsym (h[2], "foo");
47   puts ("\nnow calling `foo'");
48   fflush (stdout);
49   fp ();
50   puts ("managed to call `foo'");
51   fflush (stdout);
52 
53   dlclose (h[2]);
54 
55   puts ("\nAfter unloading \"unload2dep.so\":");
56   OUT;
57 
58   return 0;
59 }
60