Program termination (exit, atexit)

Exception handling

//atexit registers a function to run when the program ends;
//they run in reverse order of registration
void closeLog(void) {
    printf("closeLog\n");
}

void saveData(void) {
    printf("saveData\n");
}

//exit ends the program from any function: the atexit functions run,
//open files are flushed and closed, and the code goes to the system
void finish(bool ok) {
    exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);
}

int main(void) {
    atexit(closeLog);
    atexit(saveData);

    printf("working\n");
    finish(true);

    printf("not printed\n");
    //return from main is the same as exit with this code
    return EXIT_SUCCESS;
}
//printed:
//working
//saveData
//closeLog

//the code is 0 (EXIT_SUCCESS), anything else means a failure:
//in the shell ./app && echo ok prints ok only after code 0.
//_Exit(code) and abort() end the program at once,
//without the atexit functions and without flushing files