Read/write into a device in C++

18,680

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
Share:
18,680
Daniel
Author by

Daniel

Updated on June 17, 2022

Comments

  • Daniel
    Daniel about 2 years

    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?

  • Daniel
    Daniel about 13 years
    Its binary data, I know the protocol, but it doesn't specify how much bytes it sends back, so I need to know somehow if I can read and how much.
  • Jason
    Jason about 13 years
    Well, you could use fstream::read() to get back the bytes, and load it into an internally allocated buffer ... basically the same approach you'd use in C with read() and a file-descriptor allocated using open(). Otherwise you could create some object that manages it's own internal memory buffers, and overload the operator>> function to work with your custom reader object.
  • Daniel
    Daniel about 13 years
    the problem is that it will block if there is nothing to read, I need to not read if there is nothing to read.