Is it possible to call the code after completion in a C program?

In C ++, if I want the code to call something bad, I can put the code in a destructor or try-catch.

Is there a similar technique in C, as a result of which, if the program terminates unexpectedly, can I call a certain procedure (to clear the resources)?

+4
source share
3 answers

In C, you use the standard C library function atexit, which allows you to specify a function voidthat does not require calling parameters when the program terminates (conceptually, when the closing bracket is the }first call main).

You can register up to 32 of these functions in portable C and call them in the reverse order in which they were registered.

. http://en.cppreference.com/w/c/program/atexit

+6

, : sigaction (2)

, , , - :

CTRL + c:

#include <signal.h>
#include <stdio.h>

void handle_signal(int);

int main(int argc, char* argv[])
{
    //Setup Signal handling
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = handle_signal;
    sigaction(SIGINT, &sa, NULL);
    ...
}

void handle_signal(int signal)
{
    switch (signal) {
        case SIGINT:
            your_cleanup_function();
            break;
        default:
            fprintf(stderr, "Caught wrong signal: %d\n", signal);
            return;
    }
}

, (7), .

+2

, try-catch C. .

C goto .

void foo()
{
    if (!doA())
        goto exit;
    if (!doB())
        goto cleanupA;
    if (!doC())
        goto cleanupB;

    /* everything has succeeded */
    return;

cleanupB:
    undoB();
cleanupA:
    undoA();
exit:
    return;
}

fooobar.com/questions/9538/...

0

Source: https://habr.com/ru/post/1692621/


All Articles