简答:
perf stat 自动返回它正在运行的程序的退出代码。问题是你试图从你的 shell 中获取返回码。
更长的答案:
您的示例中发生的情况是,当您运行 ./a.out 程序时,它会产生段错误。 Bash(或任何你的 shell)捕获段错误并适当地设置返回值。
当您使用perf stat 运行命令时,不会为出现段错误的程序设置退出代码。因此,您会得到一个 0 退出代码来表示 perf 本身正确退出(对于 perf 将退出代码设置为 segfault 的退出代码可能会产生误导,因为在这种情况下 perf 没有 segfault)。
要获得段错误(或其他异常终止)退出代码结果,您可以使用帮助脚本从 shell 获取返回代码,然后将其返回给 perf。例如以下对我有用:
#!/bin/bash
`/bin/bash -c "$@"`
使用此wrapper.sh 脚本调用您的./a.out 程序,使用perf stat 给出所需的返回码139。
$ perf stat ./wrapper.sh ./a.out
Performance counter stats for './wrapper.sh ./a.out':
9.959972 task-clock (msec) # 0.766 CPUs utilized
5 context-switches # 0.502 K/sec
3 cpu-migrations # 0.301 K/sec
464 page-faults # 0.047 M/sec
16,413,813 cycles # 1.648 GHz
7,262,551 stalled-cycles-frontend # 44.25% frontend cycles idle
4,830,727 stalled-cycles-backend # 29.43% backend cycles idle
22,785,421 instructions # 1.39 insns per cycle
# 0.32 stalled cycles per insn
4,699,645 branches # 471.853 M/sec
124,437 branch-misses # 2.65% of all branches
0.013010875 seconds time elapsed
$ echo $?
139