红联Linux门户
Linux帮助

Linux下获取线程ID的方法

发布时间:2016-07-30 15:11:47来源:linux网站作者:六个九十度
Linux下多线程程序发生coredump时,用:
gdb /path/to/program/file core
 
可以看到所有线程:
root@rubic:~/test/thread# gdb a.out core
GNU gdb (GDB) 7.6.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-slackware-linux".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/test/thread/a.out...done.
[New LWP 826]
[New LWP 825]
 
但是哪个线程才是导致coredump的线程呢?
 
一般用gettid()函数就可以得到,但gittid在默认配置下会链接失败,这时就要靠系统调用出马了。
 
代码如下:
#include <stdio.h>  
#include <sys/syscall.h>//Linux system call for thread id  
#include <assert.h>  
#include <pthread.h>  
void *nbi(void *arg)  
{  
int i;  
printf("child thread lwpid = %u\n", syscall(SYS_gettid));  
printf("child thread tid = %u\n", pthread_self());  
scanf("%d", i);//code dump  
}  
int main()  
{  
pthread_t tid;  
int rc;  
printf("main thread lwpid = %u\n", syscall(SYS_gettid));  
printf("main thread tid = %u\n", pthread_self());  
rc = pthread_create(&tid, NULL, nbi, NULL);  
assert(0 == rc);  
pthread_join(tid, NULL);  
return 0;  
}  
 
运行结果:
root@rubic:~/test/thread# ./a.out
main thread lwpid = 825
main thread tid = 3076090112
child thread lwpid = 826
child thread tid = 3076086592
12
Segmentation fault (core dumped)
 
coredump原因:
(gdb) bt
#0  0xb75ed50e in __GI__IO_vfscanf () from /lib/libc.so.6
#1  0xb75fc183 in __isoc99_scanf () from /lib/libc.so.6
#2  0x080486ca in nbi (arg=0x0) at test.c:12
#3  0xb7728955 in start_thread () from /lib/libpthread.so.0
#4  0xb767e1ae in clone () from /lib/libc.so.6
(gdb) 
向0x0000000c(保留地址)写数据导致sigsegv
 
本文永久更新地址:http://www.linuxdiyf.com/linux/22859.html