Linux下獲取線程TID的方法——gettid()


http://blog.csdn.net/delphiwcdj/article/details/8476547

如何獲取進程的PID(process ID)?

可以使用:

  1. #include <unistd.h>  
  2. pid_t getpid(void);  

通過查看頭文件說明,可以得到更詳細的信息:

  1. find /usr/include -name unistd.h  
  2.   
  3. /usr/include/asm/unistd.h  
  4. /usr/include/bits/unistd.h  
  5. /usr/include/linux/unistd.h  
  6. /usr/include/sys/unistd.h  
  7. /usr/include/unistd.h  
  8.   
  9. cat /usr/include/unistd.h | grep getpid  
  10.   
  11. /* Get the process ID of the calling process.  */  
  12. extern __pid_t getpid (void) __THROW;  

 

 

如何獲取線程的TID(thread ID)?

通過查看man得到如下描述:
(1) The gettid() system call first appeared on Linux in kernel 2.4.11.
(2) gettid() returns the thread ID of the current process. This is equal to the process ID (as returned by getpid(2)), unless the process is part of a thread group (created by specifying the CLONE_THREAD flag to the clone(2) system call). All processes in the same thread group have the same PID, but each one has a unique TID.
(3) gettid() is Linux specific and should not be used in programs that are intended to be portable. (如果考慮移植性,不應該使用此接口)

但是根據man的使用說明,測試后發現會報找不到此接口的錯誤“error: undefined reference to `gettid'”,通過下面鏈接可以找到更詳細的說明:
http://www.kernel.org/doc/man-pages/online/pages/man2/gettid.2.html
(1) Glibc does not provide a wrapper for this system call; call it using syscall(2).(說明Glibc並沒有提供此接口的聲明,此接口實際使用的是系統調用,使用者可以自己創建包裹函數)
(2) The thread ID returned by this call is not the same thing as a POSIX thread ID (i.e., the opaque value returned by pthread_self(3)).

然后查看/usr/include/sys/syscall.h(實際在/usr/include/asm/unistd.h)可以找到我們需要的system call number:
#define __NR_gettid     224

因此,要獲取某個線程的TID,最nasty的方式是:

  1. #include <sys/syscall.h>  
  2. printf("The ID of this thread is: %ld\n", (long int)syscall(224));  

或者比較elegant的方式是:

  1. #include <sys/syscall.h>  
  2. #define gettidv1() syscall(__NR_gettid)  
  3. #define gettidv2() syscall(SYS_gettid)  
  4. printf("The ID of this thread is: %ld\n", (long int)gettidv1());// 最新的方式  
  5. printf("The ID of this thread is: %ld\n", (long int)gettidv2());// traditional form  

PS: 在/usr/include/sys/syscall.h中可以看到關於__NR_<name>和SYS_<name>兩個宏的區別,實際最后使用的都是__NR_<name>。

  1. // /usr/include/bits/syscall.h  
  2. #define SYS_gettid __NR_gettid  
  3.   
  4. #ifndef _LIBC  
  5. /* The Linux kernel header file defines macros `__NR_<name>', but some      
  6.    programs expect the traditional form `SYS_<name>'.  So in building libc 
  7.    we scan the kernel's list and produce <bits/syscall.h> with macros for 
  8.    all the `SYS_' names.  */  
  9. # include <bits/syscall.h>  
  10. #endif  

 

驗證TID是否正確的方法:
查看進程pid
(1) ps ux | grep prog_name
(2) pgrep prog_name 
查看線程tid
(1) ps -efL | grep prog_name
(2) ls /proc/pid/task


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM