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

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

So,

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

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


当前回答

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

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

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

其他回答

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

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

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

Strace列出它所应用的进程所执行的所有系统调用。如果您不知道系统调用是什么意思,那么您将无法从中获得很多好处。

然而,如果您的问题涉及到文件、路径或环境值,在有问题的程序上运行strace并将输出重定向到一个文件,然后在该文件中获取path/file/env字符串,这可能有助于您了解程序实际试图做什么,而不是您期望它做什么。

Strace概述 Strace可以看作是一个轻量级调试器。它允许程序员/用户快速发现程序是如何与操作系统交互的。它通过监控系统调用和信号来做到这一点。

使用 当你没有源代码或者不想被打扰去真正浏览它的时候,这很好。 此外,如果您不喜欢打开GDB,而只是对理解外部交互感兴趣,那么对于您自己的代码也很有用。

这是一个很好的介绍 下面是一个使用strace来调试进程挂起的温和介绍

Strace可以用作调试工具,也可以用作原语分析器。

As a debugger, you can see how given system calls were called, executed and what they return. This is very important, as it allows you to see not only that a program failed, but WHY a program failed. Usually it's just a result of lousy coding not catching all the possible outcomes of a program. Other times it's just hardcoded paths to files. Without strace you get to guess what went wrong where and how. With strace you get a breakdown of a syscall, usually just looking at a return value tells you a lot.

剖析是另一个用途。您可以使用它来分别计时每个系统调用的执行,或者作为一个聚合。虽然这可能不足以解决您的问题,但至少可以大大缩小潜在嫌疑人的范围。如果您在单个文件上看到大量的fopen/close对,那么您可能在每次执行循环时都不必要地打开和关闭文件,而不是在循环之外打开和关闭它。

Ltrace是strace的近亲,也非常有用。你必须学会区分你的瓶颈在哪里。如果执行的总时间是8秒,而你在系统调用上只花了0.05秒,那么对程序进行分段不会有什么好处,问题出在你的代码中,这通常是一个逻辑问题,或者程序实际上需要花那么长时间来运行。

The biggest problem with strace/ltrace is reading their output. If you don't know how the calls are made, or at least the names of syscalls/functions, it's going to be difficult to decipher the meaning. Knowing what the functions return can also be very beneficial, especially for different error codes. While it's a pain to decipher, they sometimes really return a pearl of knowledge; once I saw a situation where I ran out of inodes, but not out of free space, thus all the usual utilities didn't give me any warning, I just couldn't make a new file. Reading the error code from strace's output pointed me in the right direction.

简单地说,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