What's the proper way to cleanup an infinite loop application in Linux?

c, c++, cross-platform, linux, windows

Solution

Using a `SIGINT` handler is actually the normal way to handle these things in the POSIX world, and similar to using `SetConsoleCtrlHandler` in Windows.

In the `SIGINT` signal handler, you set a flag, and the loop checks this flag if it should exit or not.

However, it's not strictly needed, unless you have special needs in your cleanup (like for example sending a goodbye-message to other applications or similar). The OS will make sure all files are closed properly, all memory allocations are free'd, etc. Just the same as in Windows.

Problem

I come from a primarily Windows environment, so I'm a bit lost making a transition to writing some things in Linux. Say I've got a simple C/C++ application like so: ``` int main(int argc, char** argv) { int h = open("something"); while (true) { // do work usleep(10000); } close(h); } ``` In Windows, I'd use something like `GetAsyncKeyState()` (or some other sort of keyboard checking functionality) to look for say the escape key, and break out of my loop when it was pressed. That way my `close(h)` would get called, and I'd do all the cleanup I need to. The way I've been terminating my applications in Linux has been using CTRL+C, which from my reading means it sends `SIGINT`, and is a 'friendly' way to cause an application to quit. However, in my experience, that's just caused it to sorta drop everything and close wherever it was when it got that signal (meaning my post-loop cleanup never runs.) Some have suggested I use `signal()` to listen for `SIGINT`, but others disagree with that method. (Plus, it tends to create a bit more differences between how things are done between Windows and Linux, and I'd like to stay as close as possible to running on both platforms.) Is there a 'best practice' for things like this?

Original source