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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With