2017-06-01 55 views
0

我使用dlopen爲我的項目製作了插件。如何知道沒有.so當dlopen()

我想讓我的主程序停止嘗試再次加載插件,當沒有這樣的。

有沒有什麼好的解決方案呢? 我需要比較錯誤消息嗎?

請幫我

回答

0

manpage

如果dlopen()由於某種原因失敗時,它返回NULL

還有一個非常廣泛的例子。

下面的程序加載(glibc的)數學庫中查找cos(3)函數的 地址,並打印的2.0餘弦。所述 以下是建築物的例子,並且運行該程序:

$ cc dlopen_demo.c -ldl 
$ ./a.out 
-0.416147 

程序源

#include <stdio.h> 
#include <stdlib.h> 
#include <dlfcn.h> 
#include <gnu/lib-names.h> /* Defines LIBM_SO (which will be a 
           string such as "libm.so.6") */ 
int 
main(void) 
{ 
    void *handle; 
    double (*cosine)(double); 
    char *error; 

    handle = dlopen(LIBM_SO, RTLD_LAZY); 
    if (!handle) { 
     fprintf(stderr, "%s\n", dlerror()); 
     exit(EXIT_FAILURE); 
    } 

    dlerror(); /* Clear any existing error */ 

    cosine = (double (*)(double)) dlsym(handle, "cos"); 

    /* According to the ISO C standard, casting between function 
     pointers and 'void *', as done above, produces undefined results. 
     POSIX.1-2003 and POSIX.1-2008 accepted this state of affairs and 
     proposed the following workaround: 

      *(void **) (&cosine) = dlsym(handle, "cos"); 

     This (clumsy) cast conforms with the ISO C standard and will 
     avoid any compiler warnings. 

     The 2013 Technical Corrigendum to POSIX.1-2008 (a.k.a. 
     POSIX.1-2013) improved matters by requiring that conforming 
     implementations support casting 'void *' to a function pointer. 
     Nevertheless, some compilers (e.g., gcc with the '-pedantic' 
     option) may complain about the cast used in this program. */ 

    error = dlerror(); 
    if (error != NULL) { 
     fprintf(stderr, "%s\n", error); 
     exit(EXIT_FAILURE); 
    } 

    printf("%f\n", (*cosine)(2.0)); 
    dlclose(handle); 
    exit(EXIT_SUCCESS); 
} 
相關問題