I have a function that I want to run whenever my program exits:
void foo() {
std::cout<< \"Exiting\" << std::endl;
}
How do I reg
The only way (in Unix and Unix-like operating systems) to regain control after a process exits is to wait(2)
for it. Short of a powerfail, kernel panic, or forced reboot, this should work:
#include
#include
#include
int AtExit() {
pid_t pid = fork();
if(pid < 0) return pid;
if(pid == 0) return pid;
pid = waitpid(pid, 0, 0);
return pid;
}
int main () {
if(AtExit()) {
std::cout << "Exiting\n";
return 0;
}
std::cout << 7 << "\n";
}