获取在进程中使用pthread_created创建的所有thread_id

pie*_*fou 6 pthreads

如果有任何"智能"方法来获取在进程内threadID创建的所有s ,则使用pthreads pthread_created假设这些线程是在第三方库中创建的,不会公开这些数据.

sho*_*nex 8

一种方法是为pthread_create创建替换函数,并使用LD_PRELOAD.当然你不想重新实现pthread_create,所以你必须以某种方式调用pthread_create,但你可以要求动态加载器为你加载它:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <bits/pthreadtypes.h>
#include <dlfcn.h>

void store_id(pthread_t  * id) {
    fprintf(stderr, "new thread created with id  0x%lx\n", (*id));
}

#undef pthread_create

int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start)(void *), void * arg)
{
    int rc;
    static int (*real_create)(pthread_t * , pthread_attr_t *, void * (*start)(void *), void *) = NULL;
    if (!real_create)
        real_create = dlsym(RTLD_NEXT, "pthread_create");

    rc = real_create(thread, attr, start, arg);
    if(!rc) {
        store_id(thread);
    }
    return rc;
}
Run Code Online (Sandbox Code Playgroud)

然后将其编译为共享库:

gcc -shared -ldl -fPIC pthread_interpose.c -o libmypthread.so
Run Code Online (Sandbox Code Playgroud)

您可以将它与任何动态链接的编程一起使用:

 LD_PRELOAD=/path/to/libmypthread.so someprog
Run Code Online (Sandbox Code Playgroud)

注意:这是此博客文章的附加版本