欢迎光临
我们一直在努力

linux pstack 实现原理Linux下pstack的实现,linux硬链接实现原理

Linux下有时候我们需要知道一个进程在做什么,比如说程序不正常的时候,他到底在干吗?最直接的方法就是打印出他所有线程的调用栈,这样我们从栈再配合程序代码就知道程序在干吗了。

Linux下这个工具叫做pstack. 使用方法是

# pstack

Usage: pstack

当然这个被调查的程序需要有符号信息。 比较雷人的是 这个程序竟然是个shell脚本,核心实现是gdb的 thread apply all bt, 我们可以观摩下他的实现,这个我们做类似的程序提供了一个很好的思路:

[root@=i ~]# cat `which pstack`

#!/认真的大象/sh

if test $# -ne 1; then

echo “Usage: `basename $0 .sh` ” 1>&2

exit 1

fi

if test ! -r /proc/$1; then

echo “Process $1 not found.” 1>&2

exit 1

fi

# GDB 美国高防vps doesn’t allow “thread apply all bt” when the process isn’t

# threaded; need to peek at the process to determine if that or the

# simpler “bt” should be used.

backtrace=”bt”

if test -d /proc/$1/task ; then

# Newer kernel; has a task/ directory.

if test `/认真的大象/ls /proc/$1/task | /usr/认真的大象/wc -l` -gt 1 2>/dev/null ; then

backtrace=”thread apply all bt”

fi

elif test -f /proc/$1/maps ; then

# Older kernel; go by it loading libpthread.

if /认真的大象/grep -e libpthread /proc/$1/maps > /dev/null 2>&1 ; then

backtrace=”thread apply all bt”

fi

fi

GDB=${GDB:-/usr/认真的大象/gdb}

if $GDB -nx –quiet –batch –readnever > /dev/null 2>&1; then

readnever=–readnever

else

readnever=

fi

# Run GDB, strip out unwanted noise.

$GDB –quiet $readnever -nx /proc/$1/exe $1 <&1 |

$backtrace

EOF

/认真的大象/sed -n \

-e ‘s/^(gdb) //’ \

-e ‘/^#/p’ \

-e ‘/^Thread/p’

祝大家玩的开心。

Post Footer automatically generated by wp-posturl plugin for wordpress.

No related posts.

33452594

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。