How should I deal with resource cleanup on interru...
# kotlin-native
m
How should I deal with resource cleanup on interrupt signals? I had a look at https://dev.to/mreichelt/handling-sigint-in-kotlin-native-2ac6 but it seems like a staticCFunction can't take local variables to stop the loop or similar.
Copy code
var loop = true
        // TODO: Make this compatible with windows
        signal(SIGINT, staticCFunction<Int, Unit> {
            loop = false
        })
        while (loop) {
            Pa_Sleep(20)  // Sleep 20ms
        }
        io.cleanup()
        Pa_Terminate()
e
POSIX signal API is quite limiting whether you're in C or Kotlin
as the callback is static, it can only reference globals
m
Then what should I do to handle ^C? I didn't see any methods for it in stdlib (not that stdlib really adds many platform-independent functions in the first place)
e
it can set a global variable which you check in your loop
in C, your only options are to do that or to use siglongjmp, but the latter isn't an option in K/N, so use the former
n
Top level functions can be called in the event handlers.
e
yes, but the general rule is that only async-signal-safe functions may be called from signal handlers, or else unintended program behavior may rise
as Kotlin doesn't document anything as being async-signal-safe, do as little as possible from your signal handlers
n
Just delegate the heavy duty work from the event handler to dedicated functions. The Kotlin Native Runtime does get in the way at times; be aware when the KN Runtime is throwing runtime errors that widespread changes (mainly minor ones) might need to be made to the program.
e
if you are call a function from a signal handler, you are still in the signal handler. you need to return or siglongjmp out of it in order to be in a state that is safe to call non-async-signal-safe functions.