获取进程中使用 pthread_created 创建的所有 thread_id [英] get all the thread_id created with pthread_created within an process
问题描述
如果有任何智能"方式来获取进程内使用 pthread_created
创建的所有 threadID
,则使用 pthreads,假设这些线程是在第三方库中创建的不会暴露这些数据.
一种方法是为 pthread_create 创建一个替换函数,并使用 LD_PRELOAD.当然你不想重新实现 pthread_create,所以你必须以某种方式调用 pthread_create,但你可以让动态加载器为你加载它:
#define _GNU_SOURCE#include #include #include #include void store_id(pthread_t * id) {fprintf(stderr, "用 id 0x%lx\n 创建的新线程", (*id));}#undef pthread_createint pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start)(void *), void * arg){国际RC;static int (*real_create)(pthread_t *, pthread_attr_t *, void * (*start)(void *), void *) = NULL;如果(!real_create)real_create = dlsym(RTLD_NEXT, "pthread_create");rc = real_create(thread, attr, start, arg);如果(!rc){store_id(线程);}返回 rc;}
然后将其编译为共享库:
gcc -shared -ldl -fPIC pthread_interpose.c -o libmypthread.so
并且您可以将它与任何动态链接的程序一起使用:
LD_PRELOAD=/path/to/libmypthread.so someprog
注意:这是此博文
Using pthreads if there is any "intelligent" way to get all the threadID
s created using pthread_created
within an process, supposing those threads are created in the third party library that does not expose those data.
One way to do it is to create a replacement function for pthread_create, and use the LD_PRELOAD. Of course you don't want to reimplement pthread_create, so you have to call pthread_create somehow, but you can ask the dynamic loader to load it for you :
#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;
}
Then you compile it to a shared library :
gcc -shared -ldl -fPIC pthread_interpose.c -o libmypthread.so
And you can use it with any dynamically linked prog :
LD_PRELOAD=/path/to/libmypthread.so someprog
Note : This is an adpated version of this blog post
这篇关于获取进程中使用 pthread_created 创建的所有 thread_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!