How can a C program poll for user input while simultaneously performing other actions in a Linux environment?

Your task requires an event loop based on select or epoll. One event it would wait for is user input - when STDIN_FILENO becomes ready for read. Another is the 1-second periodic timer when you need to poll the controller.

There are quite a few libraries that implement an event loop for you so that you can focus on what events you need to handle and how. libevent is one of the oldest, feature rich and popular.


I believe that the "Unix" way would be not to ask for user input, but to react to a user signal. For example, when the user presses Ctrl-C, the currently running process receives SIGINT.

An example how to properly use SIGINT to interrupt a loop can be found here. Copying it into the answer in case the link gets stale:

#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static volatile sig_atomic_t got_signal = 0;

static void my_sig_handler(int signo)
{
    got_signal = 1;
}

int main()
{
    struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_handler = &my_sig_handler;
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("sigaction");
        return EXIT_FAILURE;
    }

    for (;;) {
        if (got_signal) {
            got_signal = 0;
            printf("Received interrupt signal!\n");
        }
        printf("Doing useful stuff...\n");
        sleep(1); /* Sleep is not only useful, it is essential! */
    }
    return EXIT_SUCCESS;
}

(in your case it would be a good idea to put break; into the if block or to use while(!got_signal))


Simple answer is multi-threading, where you have thread deployed to wait for user input, while loop continues on. So have this:

char flag = 1;

while (flag) {
     // run the loop

     // if thing happens deploy the thread which will ask user for input

}

I have not done threading in a while, I think this page would be better than me trying to explain it to you: https://randu.org/tutorials/threads/

Tags:

Linux

C