Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

Background:

I'm a relatively inexperienced developer trying to write software to interface with a PCI motion controller. I'm using C (compiled with gcc) on Ubuntu Linux 18.04.

The program I'm writing needs to regularly check for unsolicited status messages sent by the motion controller (approx. once per second) and display any messages it finds on a terminal screen (for which I'm using the ncurses library).

What I have:

Right now, to do this, I'm calling a function that checks for unsolicited messages in a while loop. The code is roughly akin to:

while (1)
{
    // check for messages from PCI and store them in a traffic buffer
    checkForMessages(PCIconnection, trafficBuffer);

    // output the traffic buffer to the screen
    printf("%s", trafficBuffer);    
}

What I need:

I need the user to be prompted for input in a way that allows them to end the loop. For example, the user could input end causing the loop to stop and the program to continue.

The problem:

I'm not aware of a way to achieve this without putting fgets inside the while loop, causing the program to stop and wait for the user to input something on every loop iteration.

I've looked for a solution, but I haven't been able to find discussion on how to achieve the functionality I need. Opening a new thread or process seems like a step in the right direction?

I'm open to completely restructuring my code if what I'm currently doing is poor practice.

Thank you for any help!

like image 488
josephsturm Avatar asked Apr 12 '19 23:04

josephsturm


1 Answers

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.

like image 188
Maxim Egorushkin Avatar answered Oct 11 '22 11:10

Maxim Egorushkin