How do you run a function on exit in C++

前端 未结 4 1796
温柔的废话
温柔的废话 2021-02-05 10:27

I have a function that I want to run whenever my program exits:

void foo() {
  std::cout<< \"Exiting\" << std::endl;
}

How do I reg

4条回答
  •  北海茫月
    2021-02-05 10:40

    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";
    }
    

提交回复
热议问题