1

在 Linux 下运行的程序可能因多种原因终止:程序可能完成所需的计算并简单地退出(正常退出),代码可能会检测到一些问题并抛出异常(提前退出),最后,系统可能会停止执行是因为程序试图做一些它不应该做的事情(例如,访问受保护的内存)(崩溃)。

有没有一种可靠且一致的方法可以区分正常/提前退出和崩溃?那是,

% any_program
...time passes and prompt re-appears...
% (type something here that tells me if the program crashed)

例如,是否存在$?表示崩溃与程序控制终止的值?

4

1 回答 1

2

The bash man page states:

 The  return  value  of a simple command is its exit status, or 128+n if
 the command is terminated by signal n.

You can check for various signals indicating a crash, such as SIGSEGV (11), and SIGABRT(6), by seeing if $? is 139 or 134 respectively:

$ any_program
$ if [ $? = 139 -o $? = 134 ]; then
>   echo "Crashed!"
> fi

At the very least, if $? is greater than 128, it indicates something unusual happened, although it may be that the user killed the program by hitting ctrl-c and not an actual crash.

于 2013-01-26T15:19:29.037 回答