tags:

views:

48

answers:

3

Hi ,

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.

+2  A: 

There is no standard way in the pthreads API for retrieving the list of threads. What you could do is dive into the source code of "ps" or "top" and see how it's done. You can find the source code in the procps library.

Eldad Mor
A: 

Read the list of folders in /proc/[your-process-pid]/task

This is a directory that contains one subdirectory for each thread in the process.

skwllsp
+2  A: 

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

shodanex