0

I know this probably already has an answer on here, but basically I need to close a session on the server when the Command Line is force closed.

  • [`std::atexit`](https://en.cppreference.com/w/cpp/utility/program/atexit) and [`std::at_quick_exit`](https://en.cppreference.com/w/cpp/utility/program/at_quick_exit) come to mind. But there is no way to ensure you always run something so the server should implement a timeout mechanism. If the user kills the program via other means it may not run exit handlers – Mgetz Nov 06 '20 at 16:38
  • See [How exactly does __attribute__((constructor)) work?](https://stackoverflow.com/a/24361145/3422102) for additional methods. – David C. Rankin Nov 06 '20 at 21:11

1 Answers1

0

Use a C++ destructor. At the beginning of your main(), define a variable with a session class like below.

class ManageSession
{
public:
   int sessionId;
   ManageSession() {
      sessionId = Connect();
   }
   ~ManageSession()
   {
      Close(sessionId);
   }

   int Connect() {
      // find and connect
      return 42;
   }
   void Close(int id) {
      if (id > 0) {
         id = 0; // close it
      }
   }
};

int main() {
   ManageSession session;

   // do amazing things
};
  • This will only work if the program exits in a controlled fashion (i.e returns from main(), one way or the other). If the program is simply killed (or calls `exit()` or `_exit()`, the ManageSession destructor will never execute. – Jeremy Friesner Nov 06 '20 at 20:47
  • @JeremyFriesner: Yes, adding an exception handler in main an/or using set_terminate() function will allow some processing on unexpected exits. – un-CharlieH Nov 09 '20 at 17:35