Page 1 of 1

C Do Something Independent of User Input

Posted: Tue Feb 15, 2022 5:53 pm
by PavelChekov
I am very proficient in C, and I don't think that there is a way to do this, but I'm going to ask before I give up:

I have a loop, and I want to do something every iteration, but I want to let the user interrupt whats going on with input. Is there a way to do this in C?

Thanks

Re: C Do Something Independent of User Input

Posted: Tue Feb 15, 2022 7:02 pm
by klange
Pure C, as in what's defined in the standard without getting into 'extensions' like POSIX or win32 or whatever, does have signals. It does not specify how those signals can be introduced by a user, but they at least exist, and while the core standard only defines six, one of them is SIGINT. So, even in pure standard C you can expect to be able to catch SIGINT in a signal handler and change a condition in your loop.

Re: C Do Something Independent of User Input

Posted: Tue Feb 15, 2022 7:47 pm
by alexfru
To do it cleanly in mostly pure C, you need to consider all loops (across all levels of the call stack) that may take a lot of time (or unpredictable amount of time, perhaps, due to blocking) and make them check for your condition/event on every iteration (e.g. read a global/volatile variable) and exit. You also most likely need to organize the code in such a way that those same loops can be reentered once the condition/even is cleared/handled.

While abandoning everything and exiting loops and returning to the caller seems easy and can even be delegated to longjmp() (not without longjmp()'s own problems), actually resuming those broken loops is tricky. You need to preserve enough state around every loop so you can pick things up and loop again.

This naturally throws you into the world of state machines.