You might not have to go that low-level. If you set on_exit to your cleanup function, it would automatically run before GS closes. (Be sure to check if on_exit is already defined so you don't mess up the other programmers' exit routine.)