how to detect Game Engine Exit?

I’m running a script which calls two other scripts;
script #1 opens a memory mapped file which stays open while the game is played.
script #2 opens a sockets connection to another machine on my network.

When Blender Game Engine is closed, I need to flush+save the mmap file and terminate the socket connection.
How do I do that?