Debian Codegraph @

listings/chapter-11/module.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <dlfcn.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11
12 #include "server.h"
13
14 char* module_dir;
15
16 struct server_module* module_open (const char* module_name)
17 {
18 char* module_path;
19 void* handle;
20 void (* module_generate) (int);
21 struct server_module* module;
22
23 /* Construct the full path of the module shared library we'll try to
24 load. */
25 module_path =
26 (char*) xmalloc (strlen (module_dir) + strlen (module_name) + 2);
27 sprintf (module_path, "%s/%s", module_dir, module_name);
28
29 /* Attempt to open MODULE_PATH as a shared library. */
30 handle = dlopen (module_path, RTLD_NOW);
31 free (module_path);
32 if (handle == NULL) {
33 /* Failed; either this path doesn't exist, or it isn't a shared
34 library. */
35 return NULL;
36 }
37
38 /* Resolve the module_generate symbol from the shared library. */
39 module_generate = (void (*) (int)) dlsym (handle, "module_generate");
40 /* Make sure the symbol was found. */
41 if (module_generate == NULL) {
42 /* The symbol is missing. While this is a shared library, it
43 probably isn't a server module. Close up and indicate failure. */
44 dlclose (handle);
45 return NULL;
46 }
47
48 /* Allocate and initialize a server_module object. */
49 module = (struct server_module*) xmalloc (sizeof (struct server_module));
50 module->handle = handle;
51 module->name = xstrdup (module_name);
52 module->generate_function = module_generate;
53 /* Return it, indicating success. */
54 return module;
55 }
56
57 void module_close (struct server_module* module)
58 {
59 /* Close the shared library. */
60 dlclose (module->handle);
61 /* Deallocate the module name. */
62 free ((char*) module->name);
63 /* Deallocate the module object. */
64 free (module);
65 }