Add Book to My BookshelfPurchase This Book Online

Chapter 16 - Miscellaneous Routines

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Exiting When Errors Occur
When debugging a program, a core dump of the program's current state to examine with a debugger is invaluable. As discussed in Chapter 10, Signals, a number of events will cause the operating system to send a signal to a process that causes a core dump. But there are a wide variety of other circumstances when it would be nice to have a core dump and the operating system doesn't know anything is wrong.
The abort function can be used to generate a core dump at any time:
    #include <stdlib.h>
    void abort(void);
When called, abort attempts to close all open files, and then sends a SIGABRT signal to the calling process. If the process is not catching or ignoring this signal, a core dump results.
The assert function (actually, it's a preprocessor macro) provides an easy way to use abort in debugging:
    #include <assrt.h>
    void assert(int expression);
The assert macro evaluates expression and if it evaluates to false (0), prints a line on the standard error output containing the expression, the source filename, and the line number, and then calls abort.
Example 16-1 shows a small program that accepts numbers as arguments, adds them together, and prints the total. Before printing the total, it uses assert to check that the total is greater than 100. If it isn't, assert will print an error message and call abort.
Example 16-1:  assert
#include <assert.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
    int total;
    total = 0;
    while (--argc)
        total += atoi(*++argv);
    assert(total > 100);
    printf("%d\n", total);
    exit(0);
}
    % assert 10 20 30 40 50
    150
    % assert 1 2 3 4 5
    assert.c:14: failed assertion 'total > 100'
    Abort (core dumped)

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback