tags:

views:

41

answers:

1

I developed a process with some threads on a Linux machine (Ubuntu). I'd like to know how can i get LWP from each thread (using a glibc function), once the PID and PPID are always the same for all the threads of the process.

UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD
root      2588  2587  2588  0   11 00:05 ?        00:00:07 ./testsrv
root      2588  2587  2589  2   11 00:05 ?        00:23:17 ./testsrv
root      2588  2587  2590  0   11 00:05 ?        00:00:00 ./testsrv
root      2588  2587  2591  0   11 00:05 ?        00:00:03 ./testsrv
root      2588  2587  2592  0   11 00:05 ?        00:00:00 ./testsrv
root      2588  2587  2593  0   11 00:05 ?        00:00:00 ./testsrv
root      2588  2587  2594  0   11 00:05 ?        00:05:05 ./testsrv
root      2588  2587  2595  0   11 00:05 ?        00:00:00 ./testsrv
root      2588  2587  2596  0   11 00:05 ?        00:00:37 ./testsrv
root      2588  2587  2597  0   11 00:05 ?        00:00:00 ./testsrv
root      2588  2587  2601  0   11 00:05 ?        00:00:00 ./testsrv
+3  A: 

Use gettid() from man page:

DESCRIPTION
gettid() returns the caller's thread ID (TID). In a single-threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one has a unique TID. For further details, see the discussion of CLONE_THREAD in clone(2).

RETURN VALUE
On success, returns the thread ID of the calling process.

Aboelnour
Unfortunately i got an error message while trying gettid(): undefined reference to `gettid'. After some hours of researching i found and tested a multiplatform solution that really works: PlatformThreadId GetCurrentThreadId(void) { #if defined(__APPLE__) return mach_thread_self(); #elif defined(_LINUX) #ifdef __NR_gettid return syscall(__NR_gettid); #else return (getpid()); #endif #endif }
Jorg B Jorge
the same from the man page: #define _GNU_SOURCE #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> int main(int argc, char *argv[]) { pid_t tid; tid = syscall(SYS_gettid); }
Aboelnour