Some legacy code, I have to wade through, unfolds some kind of problem to me. At the moment I can't change to behavior, but I can change the surrounding code.
The legacy code starts a std::thread
, which might fail and calls std::exit
. I have to know the exit code emitted to write a JSON dump for automatic computation after my program ended. This mechanism works just fine, but not if the thread calls std::exit
.
Lets break it down to following.
#include <thread>
void func() {
try {
// do something, that also might fail
}
catch (std::exception const& e) {
// process the error
std::exit(-1); // exit with what ever exit code chosen
}
}
int main() {
std::thread t1{ func };
shutdown_dump dump;
// --> register function with 'shutdown_dump' to notice exit is called and get return code emitted.
// do some other work
// but thread fails and ends before join
t1.join();
dump.set_exit_code(0);
return 0;
// dump is created in dtor of 'dump'
}
To clarify again, I CAN'T pass dump to my thread (at the moment this is unchangeable legacy code). I'm not willing to use a singleton
, which could solve the problem in some kind of way, but it adds much more problems to worry about. And yes, it is planed to rework the legacy code, so please don't get the conversation stared this way. (Doesn't everyone have to deal with some legacy code? :D )
So can I register a function somewhere, to notice std::exit
is call AND get the return code? Unfortunately std::atexit
doesn't offer the retrieval of the emitted exit code.
I can use every feature c++14
has to offer. It should work for visual studio (windows) and clang (linux) compiler. I'm willing to implement two versions for each OS.