一位同事曾经告诉我,当Linux上所有调试都失败时,最后的选择是使用strace。

我试图学习这个奇怪工具背后的科学,但我不是系统管理专家,我没有真正得到结果。

So,

它到底是什么,有什么作用? 如何以及在哪些情况下使用它? 应该如何理解和处理输出?

简而言之,简单地说,这东西是怎么工作的?


当前回答

简单地说,strace跟踪程序发出的所有系统调用及其返回码。想想诸如文件/套接字操作和许多更模糊的操作。

如果你有一些C的工作知识,这是最有用的,因为这里的系统调用更准确地代表标准C库调用。

假设您的程序是/usr/local/bin/cough。简单的使用方法:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

写入'out_file'。

所有strace输出都将转到stderr(注意,它的巨大容量通常要求重定向到文件)。在最简单的情况下,您的程序将因错误而中止,您将能够在strace输出中看到它与操作系统的最后一次交互。

如欲获得更多资料,请浏览:

man strace

其他回答

我一直使用strace来调试权限问题。技巧是这样的:

$ strace -e trace=open,stat,read,write gnome-calculator

其中gnome-calculator是您想要运行的命令。

下面是我如何使用strace挖掘网站的一些例子。希望这对你有帮助。

检查时间到第一个字节,如下所示:

time php index.php > timeTrace.txt

看看有多少百分比的动作在做什么。大量的lstat和fstat可能表明是时候清理缓存了:

strace -s 200 -c php index.php > traceLstat.txt

输出trace.txt,以便您可以准确地看到正在进行的调用。

strace -Tt -o Fulltrace.txt php index.php

使用它来检查是否有东西在0.1到0.9秒之间加载:

cat Fulltrace.txt | grep "[<]0.[1-9]" > traceSlowest.txt

查看strace中捕获了哪些丢失的文件或目录。这将输出很多涉及我们系统的东西-唯一相关的位涉及客户的文件:

strace -vv php index.php 2>&1 | sed -n '/= -1/p' > traceFailures.txt

strace -tfp PID将监控PID进程的系统调用,因此我们可以调试/监控我们的进程/程序状态。

Strace是一个很好的工具,用于了解程序如何进行各种系统调用(对内核的请求),并报告失败的调用以及与该失败相关的错误值。并不是所有的失败都是bug。例如,试图搜索文件的代码可能会得到ENOENT(没有这样的文件或目录)错误,但这可能是代码逻辑中可以接受的场景。

使用strace的一个很好的用例是在临时文件创建期间调试竞态条件。例如,通过将进程ID (PID)附加到某个预先确定的字符串来创建文件的程序在多线程场景中可能会遇到问题。PID+TID(进程id +线程id)或更好的系统调用(如mkstemp)将修复此问题。

它还适用于调试崩溃。您可能会发现这篇(我的)关于strace和调试崩溃的文章很有用。

Strace是一种突出的工具,用于研究无法在调试器下运行这些程序的生产系统。具体来说,我们在以下两种情况下使用了strace:

Program foo seems to be in deadlock and has become unresponsive. This could be a target for gdb; however, we haven't always had the source code or sometimes were dealing with scripted languages that weren't straight-forward to run under a debugger. In this case, you run strace on an already running program and you will get the list of system calls being made. This is particularly useful if you are investigating a client/server application or an application that interacts with a database Investigating why a program is slow. In particular, we had just moved to a new distributed file system and the new throughput of the system was very slow. You can specify strace with the '-T' option which will tell you how much time was spent in each system call. This helped to determine why the file system was causing things to slow down.

有关使用strace进行分析的示例,请参阅我对这个问题的回答。