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
C Do Something Independent of User Input
- PavelChekov
- Member
- Posts: 113
- Joined: Mon Sep 21, 2020 9:51 am
- Location: Aboard the Enterprise
C Do Something Independent of User Input
USS Enterprise NCC-1701,
The Final Frontier,
Space,
The Universe
Live Long And Prosper
Slava Ukraini!
Слава Україні!
The Final Frontier,
Space,
The Universe
Live Long And Prosper
Slava Ukraini!
Слава Україні!
Re: C Do Something Independent of User Input
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
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.
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.