I have a loop that constantly reads from my serial port. The loop is infinite, so the only way I know of stopping the program is by using Ctrl+C. The problem with this solution, which I suspect is causing other problems as well, is that when I use Ctrl+C, my program ends abruptly. At the end of the program, I close the connection to the file descriptor of the serial port I am accessing, but I don’t think my program ever reaches that because of me using the Ctrl+C command, which just stops the program exactly where it is.
Is there a way for me to create the infinite while loop, and exit when I want, but at the same time, maintain the capability to execute the code beneath it?
Try this and see what happens:
Ctrl-C sends a signal (SIGINT) to your process. The default action for the process is to exit when it gets it, but you can catch the signal instead and handle it gracefully.