# How to do non-blocking keyboard input reading on console app?

**URL:** <https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894>\
**Category:** Using Swift\
**Tags:** console\
**Created:** [April 29, 2019, 3:07pm UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894 "2019-04-29T15:07:49Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![MrBee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mrbee/32/2312_2.png) [@MrBee](https://forums.swift.org/u/MrBee)\
**Post date:** [April 29, 2019, 3:07pm UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/1 "2019-04-29T15:07:49Z")

</div>

Hi,

I'd like to make a simple game as console app. I want the game keeps on going with the sprite and animation (using emojis) while there's no keyboard input; and it will react accordingly if there are ones such as arrow keys to direct the actor path, etc. However, I don't know how to do it using Swift (v5).

I knew there's `termios()` in Darwin module but I found it incompatible with many C examples out there. Any hints, please?

Thank you.

~Bee

---

<div class="post-metadata">

**Author:** ![nuclearace](https://avatars.discourse-cdn.com/v4/letter/n/51bf81/32.png) [@nuclearace](https://forums.swift.org/u/nuclearace)\
**Post date:** [April 29, 2019, 6:31pm UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/2 "2019-04-29T18:31:59Z")

</div>

You probably want to look into [Dispatch](https://developer.apple.com/documentation/dispatch). It's the goto for things dealing with asynchronous processing.

---

<div class="post-metadata">

**Author:** ![MrBee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mrbee/32/2312_2.png) [@MrBee](https://forums.swift.org/u/MrBee)\
**Post date:** [April 30, 2019, 12:12am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/3 "2019-04-30T00:12:24Z")

</div>

I don't think I would need Dispatch. There's some configurations in Terminal via `termios()` to make it non-blocking. But I don't know how to do it in Swift.

---

<div class="post-metadata">

**Author:** ![TellowKrinkle](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tellowkrinkle/32/3370_2.png) [@TellowKrinkle](https://forums.swift.org/u/TellowKrinkle)\
**Post date:** [April 30, 2019, 12:58am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/4 "2019-04-30T00:58:32Z")

</div>

Would you mind linking one of these non-working C examples? Unless they utilize weird macros or variadic functions, you should be able to call all the C stuff you need.

---

<div class="post-metadata">

**Author:** ![MrBee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mrbee/32/2312_2.png) [@MrBee](https://forums.swift.org/u/MrBee)\
**Post date:** [April 30, 2019, 3:18am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/5 "2019-04-30T03:18:31Z")

</div>

Here a C example that I found. It works with C but I failed to convert it to Swift using Darwin module.

```nohighlight
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv);
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    int key;

    printf("press a key: ");
    fflush(stdout);

    set_conio_terminal_mode();

    while (1) {
        if (kbhit()) {
            key = getch();

            if (key == 13) {
                printf("\n\r");
                break;
            } else if (key >= 20) {
                printf("%c, ", key);
                fflush(stdout);
            }
        }
        else {
            /* do some work */
            printf(".");
            usleep(10);
            printf(".");
            usleep(10);
            printf(".");
            usleep(10);
            printf("\e[3D");
            usleep(10);
        }
    }

    reset_terminal_mode();
}

```

There are some variables and methods that don't exist in Darwin module, such as the `FD_ZERO`.

---

<div class="post-metadata">

**Author:** ![TellowKrinkle](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tellowkrinkle/32/3370_2.png) [@TellowKrinkle](https://forums.swift.org/u/TellowKrinkle)\
**Post date:** [April 30, 2019, 6:46am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/6 "2019-04-30T06:46:59Z")

</div>

It appears FD\_SET and FD\_ZERO are implemented as macros, which is why they aren't importing properly.

To get around this, add a C header to your swift project with the following declarations and them import it into your swift project using a method like [this](https://theswiftdev.com/2018/01/15/how-to-call-c-code-from-swift/):

```nohighlight
#pragma once
#include <sys/select.h>

static inline void fdset_zero(fd_set *set) { FD_ZERO(set); }
static inline void fdset_set(int fd, fd_set *set) { FD_SET(fd, set); }
static inline void fdset_clr(int fd, fd_set *set) { FD_CLR(fd, set); }
static inline int fdset_isset(int fd, fd_set *set) { return FD_ISSET(fd, set); }

```

---

<div class="post-metadata">

**Author:** ![eskimo](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/eskimo/32/13558_2.png) [@eskimo](https://forums.swift.org/u/eskimo)\
**Post date:** [April 30, 2019, 7:42am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/7 "2019-04-30T07:42:10Z")

</div>

> There are some variables and methods that don't exist in Darwin  
> module, such as the `FD_ZERO`.

The `select` you’re doing on `STDIN_FILENO` in `kbhit` [1] is equivalent to using a Dispatch source, and Dispatch sources have a much nicer projection into Swift.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

[1] Well, `kbhit` isn’t using `STDIN_FILENO`, but it should be (-:

---

<div class="post-metadata">

**Author:** ![MrBee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mrbee/32/2312_2.png) [@MrBee](https://forums.swift.org/u/MrBee)\
**Post date:** [April 30, 2019, 8:53am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/8 "2019-04-30T08:53:34Z")

</div>

Alright, I'll see what I can do with Dispatch. Thank you.

---

<div class="post-metadata">

**Author:** ![Ponyboy47](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ponyboy47/32/2605_2.png) [@Ponyboy47](https://forums.swift.org/u/Ponyboy47)\
**Post date:** [May 1, 2019, 2:58pm UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/9 "2019-05-01T14:58:45Z")

</div>

If you do end up going with select, I created an SPM package that includes the select C macros which can be imported to swift: [GitHub - Ponyboy47/CSelect: Expose some of the \<sys/select.h\> file descriptor functions for swift](https://github.com/Ponyboy47/CSelect)

---

<div class="post-metadata">

**Author:** ![MrBee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mrbee/32/2312_2.png) [@MrBee](https://forums.swift.org/u/MrBee)\
**Post date:** [May 2, 2019, 3:36am UTC](https://forums.swift.org/t/how-to-do-non-blocking-keyboard-input-reading-on-console-app/23894/10 "2019-05-02T03:36:44Z")

</div>

Thank you for the help, guys. I appreciate it. I've found the solution, using `pollfd` instead of `select` or Dispatch. The working example is here: [non-blocking keyboard input in swift - Pastebin.com](https://pastebin.com/eMSAL2MZ)
