A program can exit with a variety of different status codes.
I'd like to bind an exit handler as a catch all way of handling final tasks based on this status code.
Is it possible to dispatch on the status code from within the exit handler?
As far as I can tell, No.
Therefore, I am unable to obtain the status value, as shown in this small example:
#include <iostream>
#include <cstdlib>
int Get_Return_Code(){
//can this be implemented?
return 0;
}
void Exit_Handler() {
// how do I get the return code
// from within the exit heandler?
auto return_code = Get_Return_Code(); //?
// I'd like to make decisions based on the return code
// while inside my exit handler
if (return_code == EXIT_SUCCESS){
std::cout << "perform exit successful tasks...\n";
}
else {
std::cout << "perform exit failure tasks...\n";
}
}
int main(int argc, char** argv)
{
//bind the exit handler routine
if (std::atexit(Exit_Handler)){
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
//if an argument is passed, exit with success
//if no argument is passed, exit with failure
if (argc > 1){
std::cout << "exiting with success\n";
return EXIT_SUCCESS;
}
std::cout << "exiting with failure\n";
return EXIT_FAILURE;
}
Is there a reason that C++ does not yet include on_exit?
I'm concerned about cross-compatibility in the windows world.
in regards to the code base:
My goal for doing this, does not involve memory management. We have an existing code base. There are exit statements everywhere. When a program exits with error, I'd like to display what that error code means to the user. In my mind, this is the fastest solution without major refactoring.
The easiest and most portable solution would be to wrap your program inside a shell script or other program. This wrapping script or program can then check the exit code and display the appropriate message to the user.