How can I read/write to a device in C++? the device is in /dev/ttyPA1.
I thought about fstream but I can’t know if the device has output I can read without blocking the application.
My goal is to create and application where you write something into the terminal and it gets sent into /dev/ttyPA1. If the device has something to write back it will read it from the device and write to screen. If not it will give the user prompt to write to the device again.
How can I do this?
How can I read/write to a device in C++? the device is in /dev/ttyPA1
Share
Use
open(2),read(2), andwrite(2)to read from and write to the device (and don’t forget toclose(2)when you’re done). You can also use the C stdio functions (fopen(3)and friends) or the C++ fstream classes, but if you do so, you almost definitely want to disable buffering (setvbuf(3)for stdio, oroutFile.rdbuf()->pubsetbuf(0, 0)for fstreams).These will all operate in blocking mode, however. You can use
select(2)to test if it’s possible to read from or write to a file descriptor without blocking (if it’s not possible, you shouldn’t do so). Alternatively, you can open the file with theO_NONBLOCKflag (or usefcntl(2)to set the flag after opening) on the file descriptor to make it non-blocking; then, any call toread(2)orwrite(2)that would block instead fails immediately with the errorEWOULDBLOCK.For example: