Read from terminal when enter is pressed, but do other stuff in the mean time...
Moritz Maxeiner via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 13 14:02:39 PDT 2017
On Thursday, 13 July 2017 at 15:52:57 UTC, Dustmight wrote:
> How do I read in input from the terminal without sitting there
> waiting for it? I've got code I want to run while there's no
> input, and then code I want to act on input when it comes in.
> How do I do both these things?
As Stefan mentions, the single threaded version is basically OS
specific (and as others have said there are some wrappers
available) the multithreaded solution is fairly simple (have one
thread blocked on read(stdin), the other working, synchronize as
necessary).
If you are interested, on Linux one low level (single threaded)
version would essentially consist of:
- check on program startup whether the stdin file descriptor
refers to something that (sanely) supports readiness events (tty,
sockets, pipes, etc. - *not* regular files) using calls like
`isatty`[1] and co.
- if it's a tty, put it into "raw" mode
- get yourself an epoll instance and register stdin with it
- get a file descriptor, e.g. an eventfd, for "there's work to be
done now" and register it with the epoll instance
- have the thread wait for readiness events on the epoll instance
and deal with stdin being readable and "there's work to be done
now" events for their respective fd.
- Queue work on the eventfd as necessary (e.g. from within the
readiness handling of the previous step)
[1] http://man7.org/linux/man-pages/man3/isatty.3.html
More information about the Digitalmars-d-learn
mailing list