异想天开

What's the true meaning of light, Could you tell me why

查看进程的某一线程栈工具

日期:2014-10-17 13:52:59
  
最后更新日期:2014-11-18 16:18:54
【技术】
利用pstack打印,python切分字符串行。thread_index为先pstack查看获得。
[code lang="cpp"]
#!env python
import sys
import os
import traceback

# thread_index begin from 0
def thread_stack(pid,thread_index):
result=os.popen("pstack %d" % pid).read()
lines=result.split('\n')
begin_delim="Thread %d " % thread_index
end_delim="Thread %d " % (thread_index-1)
# print begin_delim,end_delim
is_print=False
while lines:
line=lines[:1][0]
if line.startswith(begin_delim):
is_print=True
if line.startswith(end_delim):
is_print=False
if is_print:
print line
lines=lines[1:]

if __name__=='__main__':
if len(sys.argv)<3:
print 'Usage: %s pid thread_index' % sys.argv[0]
sys.exit(0)
try:
pid=int(sys.argv[1])
thread_num=int(sys.argv[2])
thread_stack(pid,thread_num)
except Exception,e:
print traceback.format_exc()
[/code]
PS:
可以直接top -H查看对于的线程号,linux系统上面,进程和线程都是使用同一task表,其表项的index就是pid。pstack 查看这个pid即可看到对应线程的stack。