Linux下获取线程ID的方法

Linux下多线程程序发生coredump时,用

gdb /path/to/program/file core

可以看到所有线程

root@rubic:~/test/thread# gdb a.out coreGNU gdb (GDB) 7.6.1Copyright (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.outmain thread lwpid = 825main thread tid = 3076090112child thread lwpid = 826child thread tid = 307608659212Segmentation 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

旅行,不要害怕错过什么,

Linux下获取线程ID的方法

相关文章:

你感兴趣的文章:

标签云: