1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
/*
* gcc -W -Wall -pedantic -rdynamic so.c -o so -ldl
*
*
* overwrite environment variable LD_LIBRARY_PATH
* with a single directory.
*/
static int force_library_path(const char *path)
{
int ret = -1; /* error code */
char keyval[100];
const char *envvar = "LD_LIBRARY_PATH";
int status;
sprintf(keyval, "%s= %s", envvar, path);
status = putenv(keyval);
if (status == 0)
{
/*
* print the new value of envvar
*/
char *pathv = getenv(envvar);
if (pathv != NULL)
{
printf("Value of %s is %s.\n", envvar, pathv);
ret = 0; /* success */
}
}
return ret;
}
int main(void)
{
int ret = EXIT_FAILURE;
int status = force_library_path("/usr/lib");
if (status != 0)
{
fprintf(stderr, "Failed to force library path.\n");
}
else
{
void *handle;
handle = dlopen ("libm.so", RTLD_LAZY);
if (handle == NULL)
{
fprintf(stderr, "%s\n", dlerror());
}
else
{
double (*cosine)(double);
char *error;
cosine = dlsym(handle, "cos");
error = dlerror();
if(error != NULL)
{
fprintf(stderr, "%s\n", error);
}
else
{
printf("%f\n", cosine(2.0));
dlclose(handle);
ret = EXIT_SUCCESS;
}
}
}
return ret;
} |
Partager