使用动态加载的pthread库

时间:2015-10-30 18:31:15

标签: pointers segmentation-fault pthreads function-pointers dynamic-loading

得到了这个段错误,我似乎无法绕过它。将其缩小到pthread_join()函数。我正在动态加载libpthread。

int main(int argc, char **argv) 
{
    void *lib_handle;
    create pthread_c;
    join pthread_j;
    pthread_t thrd_id;

    int rc;
    char *error;

    lib_handle = dlopen("/lib/x86_64-linux-gnu/libpthread.so.0", RTLD_NOW);

    if (!lib_handle) 
    {
        fprintf(stderr, "%s\n", dlerror());
        exit(1);
    }

    pthread_c = dlsym(lib_handle, "pthread_create");
    pthread_j = dlsym(lib_handle, "pthread_join");

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

    rc = pthread_c(&thrd_id, NULL, sub, (void *)NULL);
    pthread_j(thrd_id, NULL);  // CAUSES SEGFAULT
    printf ("testing");

    dlclose(lib_handle);
    return 0;
}

void* sub (void* a)
{
    printf("Hello Thread, I'm the World!\n");
}

printf()语句显示pthread_create()正在运行。但是我需要调用pthread_join()否则程序会在线程旋转之前终止。

1 个答案:

答案 0 :(得分:0)

Turns out you must declare the join and create typedefs to use pthread_t instead of int from sys/types.h

typedef int (*create)(pthread_t, void*, void*, void*);
typedef void (*join) (pthread_t, void*);

I think i was using an int for create which worked, but doesn't work for join()