繁体   English   中英

如何使用perf stat获取程序的退出代码?

[英]How can I get exit code of program run with perf stat?

我必须得到一些具有perf stat的程序的统计信息

perf stat -o stat.log ./a.out

我还必须得到这些程序的退出代码,因为它们不会总是以0退出。假设我有简单的程序将返回SIGSEGV:

main(){*(int*)0=0;}

现在,当我运行它时,我得到:

$ ./a.out Segmentation fault (core dumped) $ echo $? 139

当我用perf运行它然而我得到

$ perf stat -o stat.log ./a.out ./a.out: Segmentation fault $ echo $? 0

我得到0,好像程序完成没有错误。

当我使用perf stat运行它时,如何获得a.out的退出代码?

编辑:a.out是blackbox,我不能以任何方式修改它。

简答:

perf stat自动返回正在运行的程序的退出代码。 问题是您正在尝试从shell获取返回代码。

更长的回答:

您的示例中发生的事情是,当您运行./a.out程序时,它会产生段错误。 Bash(或任何你的shell)捕获段错误并适当地设置返回值。

当您使用perf stat运行命令时,不会为segfaults的程序设置退出代码。 因此,你得到一个正确退出的自己退出的0退出代码(这可能会误导perf将退出代码设置为段错误,因为在这种情况下perf不会出现段错误)。

要获得段错误(或其他异常终止)退出代码结果,您可以使用帮助程序脚本从shell获取返回代码,然后将其返回到perf。 例如,以下工作对我有用:

#!/bin/bash
`/bin/bash -c "$@"`

使用此wrapper.sh脚本使用perf stat调用./a.out程序会得到所需的返回码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

你可能得到0退出代码,因为perf stat成功运行。 您应该在执行命令后立即在a.out获取退出代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM