Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/write into a device in C++

Tags:

c++

io

device

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?

like image 764
Dani Avatar asked Feb 24 '23 17:02

Dani


1 Answers

Use open(2), read(2), and write(2) to read from and write to the device (and don't forget to close(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, or outFile.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 the O_NONBLOCK flag (or use fcntl(2) to set the flag after opening) on the file descriptor to make it non-blocking; then, any call to read(2) or write(2) that would block instead fails immediately with the error EWOULDBLOCK.

For example:

// Open the device in non-blocking mode
int fd = open("/dev/ttyPA1", O_RDWR | O_NONBLOCK);
if(fd < 0)
    ;  // handle error

// Try to write some data
ssize_t written = write(fd, "data", 4);
if(written >= 0)
    ;  // handle successful write (which might be a partial write!)
else if(errno == EWOULDBLOCK)
    ;  // handle case where the write would block
else
    ;  // handle real error

// Reading data is similar
like image 163
Adam Rosenfield Avatar answered Feb 26 '23 07:02

Adam Rosenfield