![在特定时间段内运行 strace](https://linux22.com/image/40120/%E5%9C%A8%E7%89%B9%E5%AE%9A%E6%97%B6%E9%97%B4%E6%AE%B5%E5%86%85%E8%BF%90%E8%A1%8C%20strace.png)
如何在用户进程上运行 strace 特定时间段(例如 1 分钟),而不终止用户进程且不使用 Ctrl+C?
我想创建一个脚本来自动执行用户进程的 strace。
答案1
使用timeout
in GNU coreutils
,您可以执行以下操作:
- 获取进程id
- 跑步
timeout 60 strace -p PID
这是一个例子。
test.sh
:
#!/bin/bash
while :; do
echo "$$"
sleep 100
done
运行:
$ ./test.sh
27121
运行:strace
timeout
% cuonglm at ~
% timeout 60 strace -p 27121
Process 27121 attached - interrupt to quit
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 27311
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
--- SIGCHLD (Child exited) @ 0 (0) ---
wait4(-1, 0x7fff374b8598, WNOHANG, NULL) = -1 ECHILD (No child processes)
rt_sigreturn(0xffffffffffffffff) = 0
rt_sigaction(SIGINT, {0x45c4d0, [], SA_RESTORER, 0x7fcdc10e05c0}, {0x443910, [], SA_RESTORER, 0x7fcdc10e05c0}, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
write(1, "27121\n", 6) = 6
rt_sigprocmask(SIG_BLOCK, [INT CHLD], [], 8) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fcdc1a699d0) = 27328
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGINT, {0x443910, [], SA_RESTORER, 0x7fcdc10e05c0}, {0x45c4d0, [], SA_RESTORER, 0x7fcdc10e05c0}, 8) = 0
wait4(-1,
1分钟后:
....
rt_sigprocmask(SIG_BLOCK, [INT CHLD], [], 8) = 0
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fcdc1a699d0) = 27328
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGINT, {0x443910, [], SA_RESTORER, 0x7fcdc10e05c0}, {0x45c4d0, [], SA_RESTORER, 0x7fcdc10e05c0}, 8) = 0
wait4(-1, <unfinished ...>
Process 27121 detached
% cuonglm at ~
答案2
timeout
似乎是最通用的解决方案。只需键入timeout 60s command
,命令就会在 60 秒内结束。TERM
如果程序默认运行,它将发送一个。您可以使用 选项指定想要获取的信号--signal
。
持续时间可以以秒、分钟、小时或天为单位设置,每个都有一个特定的后缀来确定将使用什么。