Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all the thread_id created with pthread_created within an process

Tags:

pthreads

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.

like image 668
pierrotlefou Avatar asked Sep 14 '10 08:09

pierrotlefou


People also ask

How many threads does pthread_create create?

The maximum number of threads is dependent upon the size of the private area below 16M. pthread_create() inspects this address space before creating a new thread. A realistic limit is 200 to 400 threads.

Which type of thread is created by the pthread_create API?

the following two thread creation mechanisms are functionally equivalent: rc = pthread_create(&t, NULL, foo, NULL); rc = pthread_create(&t, &attr, foo, NULL); The cancellation state of the new thread is PTHREAD_CANCEL_ENABLE. The cancellation type of the new thread is PTHREAD_CANCEL_DEFERRED.

Does pthread_create create a process?

The pthread_create() function starts a new thread in the calling process. The new thread starts execution by invoking start_routine(); arg is passed as the sole argument of start_routine().

What does pthread_create return?

pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred. When any of the following conditions are detected, pthread_create() fails and returns the corresponding value.


1 Answers

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

like image 197
shodanex Avatar answered Jan 03 '23 02:01

shodanex