rlandster
rlandster

Reputation: 7815

Detect program-controlled termination versus crash in Linux

A program running under Linux can terminate for a number of reasons: the program might finish its needed computations and simply exit (normal exit), the code might detect some problem and throw an exception (early exit), and finally, the system might stop the execution because the program tried to do something it should not (e.g., access protected memory) (crash).

Is there a reliable and consistent way I can distinguish between normal/early exit and a crash? That is,

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

For example, are there values of $? that indicate crashes versus program-controlled termination?

Upvotes: 1

Views: 951

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

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.

Upvotes: 2

Related Questions