一、基本语法和选项
基本语法
strace [选项] 命令 [命令参数]
strace [选项] -p PID
二、常用选项分类详解
- 输出控制选项
输出格式控制
# -t 添加时间戳
strace -t command # 显示时间(时分秒)
strace -tt command # 显示时间(微秒级)
strace -ttt command # 显示自纪元以来的秒数.微秒
# -T 显示系统调用耗时
strace -T command
strace -ttT command # 组合使用
# -r 显示相对时间戳
strace -r command
# -x 以16进制显示非ASCII字符串
strace -x command
# -xx 所有字符串以16进制显示
strace -xx command
# -a 列对齐
strace -a 30 command # 设置列宽为30
# -s 设置字符串最大长度
strace -s 128 command # 默认32,设为128显示更多内容
strace -s 9999 command # 显示完整字符串
输出目标控制
# -o 输出到文件
strace -o trace.log command
# 输出到不同文件描述符
strace -e trace=write -e write=1,2 # 只跟踪写到stdout/stderr的内容
# 使用tee同时输出到屏幕和文件
strace -o >(tee trace.log) command
- 过滤选项
按系统调用类型过滤
# -e trace= 跟踪特定系统调用
strace -e trace=open,read,write command # 只跟踪文件操作
strace -e trace=network command # 网络相关
strace -e trace=file command # 文件相关
strace -e trace=process command # 进程相关
strace -e trace=memory command # 内存相关
strace -e trace=signal command # 信号相关
strace -e trace=ipc command # IPC相关
strace -e trace=desc command # 文件描述符相关
strace -e trace=all # 所有系统调用(默认)
# 常用组合
strace -e trace=file,network command
strace -e trace=open,close,read,write,connect,accept command
按系统调用参数过滤
# 跟踪特定文件
strace -e trace=open -e open=filename command
# 跟踪特定文件描述符的读写
strace -e trace=read -e read=3 command
strace -e trace=write -e write=1,2 command # stdout和stderr
# 跟踪特定信号的接收
strace -e trace=signal -e signal=SIGSEGV command
常用过滤表达式
# 只跟踪失败的系统调用
strace -e trace=open,read,write -e status=failed command
# 排除某些系统调用
strace -e trace=!openat,read,write command # 排除openat
# 复杂过滤表达式
strace -e trace=open -e open=/etc/* command
实时查看系统调用
strace - 系统调用跟踪器
# 跟踪已运行进程的系统调用
sudo strace -p PID
# 统计系统调用频率(Ctrl+C停止后显示统计)
sudo strace -c -p PID
# 只跟踪特定系统调用(如文件操作、网络操作)
sudo strace -p PID -e trace=file # 文件相关
sudo strace -p PID -e trace=network # 网络相关
sudo strace -p PID -e trace=desc # 文件描述符
sudo strace -p PID -e trace=memory # 内存相关
sudo strace -p PID -e trace=signal # 信号相关
sudo strace -p PID -e trace=ipc # IPC相关
# 详细跟踪,显示时间戳
sudo strace -p PID -tt -T
# 保存到文件分析
sudo strace -o /tmp/strace.log -p PID
# 跟踪子进程(如果进程会fork)
sudo strace -f -p PID
监控特定模式
#!/bin/bash
# monitor_errors.sh
PID=$1
ERRORS="ENOENT|EACCES|ETIMEDOUT|ECONNREFUSED"
strace -f -p $PID 2>&1 | \
while read line; do
if echo "$line" | grep -q "= -1"; then
if echo "$line" | grep -qE "$ERRORS"; then
echo "[ERROR $(date +%H:%M:%S)] $line"
fi
fi
done
常用系统调用分类:
# CPU密集型通常关注:
sudo strace -p PID -e trace=nanosleep,poll,select,futex,epoll_wait
# I/O密集型通常关注:
sudo strace -p PID -e trace=read,write,pread,pwrite,sendto,recvfrom
# 系统资源争用:
sudo strace -p PID -e trace=mmap,munmap,brk,mremap
- perf - 性能分析工具
更深入的函数级分析:
# 查看进程的CPU热点函数
sudo perf top -p PID
# 记录进程性能数据
sudo perf record -p PID -g -- sleep 30
sudo perf report
# 统计系统调用
sudo perf trace -p PID
# 实时显示系统调用
sudo perf trace -p PID -- sleep 10
# 生成火焰图
sudo perf record -F 99 -p PID -g -- sleep 60
sudo perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg