p.matsinopoulos
p.matsinopoulos

Reputation: 7810

How to programmatically send the Enter key in C

This is a C console/terminal program.

I would like to let the user wait for the program to do some background work until either the background work finishes or the user clicks on the <Enter> key. I do that with a statement:

getchar();

and I have another thread doing the background work. When the thread is about to finish, I would like the thread to send programmatically the <Enter> key so that the control continues after the getchar() statement.

How is this possible?

Upvotes: 0

Views: 542

Answers (1)

paxdiablo
paxdiablo

Reputation: 881213

The getchar() function will block until a character arrives. Though not standard C, you can use a select call in a loop to wait until a given file handle is readable, then read it. That would go something like the following demo code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>

int main(void) {
    fd_set rfds;
    struct timeval tv;
    int retval;

    puts("Waiting for a character ...");
    for (;;) {
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);

        tv.tv_sec = 1;
        tv.tv_usec = 0;

        if (select(1, &rfds, NULL, NULL, &tv) > 0) break;

        puts("Delay over, doing some stuff, then waiting ...");
    }

    int ch = getchar();
    printf("Character available, it was '%c'.\n", ch);

    return 0;
}

In your particular case, I wouldn't have an infinite loop for(;;). Rather, I'd do something like:

int stillRunning = 1;
while (stillRunning) {
   ...
}

and then have the background task set stillRunning to zero to cause the loop to exit regardless of a keypress.

Upvotes: 1

Related Questions