Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

pthreads - get all the thread_id created with pthread_created within an process

Using pthreads if there is any "intelligent" way to get all the threadIDs created using pthread_created within an process, supposing those threads are created in the third party library that does not expose those data.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", (*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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...