乐闻世界logo
搜索文章和话题

How should strace be used?

1个答案

1

"strace" is a powerful command-line tool primarily used to trace system calls and signals on UNIX and UNIX-like systems (such as Linux). When diagnosing, analyzing, or debugging a running program, strace is an invaluable tool. The following outlines how to use strace:

1. Basic Usage

  • To trace system calls for a program, enter the strace command followed by the program name and its arguments in the command line. For example:

    shell
    strace ls

    This will print all system calls made during the execution of the ls command.

2. Tracing Specific System Calls

  • If you are only interested in specific system calls, use the -e option to specify them. For example, to view all system calls related to file descriptor operations:

    shell
    strace -e trace=file ls

3. Tracing Processes

  • strace can attach to a running process by providing its PID. For example:

    shell
    strace -p 1234

    This will trace the process with PID 1234.

4. Redirecting Output to a File

  • Use the -o option to redirect strace's output to a file for further analysis. For example:

    shell
    strace -o output.txt ls

    This writes the system calls of the ls command to output.txt.

5. Filtering Output

  • The -e option not only specifies which calls to trace but also filters output to show only relevant calls. For example:

    shell
    strace -e open,close ls

    This displays only the open and close system calls made by the ls command.

6. Tracing Child Processes

  • Use the -f option to trace all child processes created by the main process. For example:

    shell
    strace -f ./my_script.sh

7. Viewing System Call Statistics

  • To view system call statistics, use the -c option. For example:

    shell
    strace -c ls

    After execution, this displays statistics such as counts, time, and errors for all system calls.

8. Setting the Maximum String Length for Tracing

  • By default, strace truncates displayed strings. Use the -s option to set the maximum string length. For example:

    shell
    strace -s 1024 ls

    This displays strings up to 1024 characters long.

Practical Example

Suppose you want to debug your program myapp, which has issues with certain file operations. Use strace to check for unexpected file read/write operations:

shell
strace -e trace=file -o strace_output.txt ./myapp

After execution, examine the strace_output.txt file. It may reveal access to unintended files or open system calls returning error codes indicating the root cause. Analyzing this output helps pinpoint the exact problem location and guide code modifications.

The above covers the basic usage and advanced options of strace to help you debug and understand program behavior more effectively.

2024年6月29日 12:07 回复

你的答案