如何使用 C++ 读取/写入设备?该设备位于 /dev/ttyPA1
。
我考虑过 fstream,但我不知道设备是否有我可以在不阻塞应用程序的情况下读取的输出。
我的目标是创建和应用程序,您可以在其中向终端写入内容并将其发送到 /dev/ttyPA1
。如果设备有东西要写回,它将从设备中读取并写入屏幕。如果不是,它将提示用户再次写入设备。
我该怎么做?
最佳答案
使用open(2)
, read(2)
, 和 write(2)
读取和写入设备(完成后不要忘记 close(2)
)。您还可以使用 C stdio 函数(fopen(3)
和 friend )或 C++ fstream 类,但如果这样做,您几乎肯定要禁用缓冲(setvbuf(3)
用于 stdio,或 outFile.rdbuf() ->pubsetbuf(0, 0)
用于 fstreams。
但是,这些都将在阻塞 模式下运行。您可以使用 select(2)
测试是否可以在不阻塞的情况下读取或写入文件描述符(如果不可能,则不应这样做)。或者,您可以在文件描述符上使用 O_NONBLOCK
标志(或使用 fcntl(2)
在打开后设置标志)打开文件,使其成为非阻塞;然后,任何对 read(2)
或 write(2)
的调用都会立即失败,并显示错误 EWOULDBLOCK
。
例如:
// 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
关于c++ - 在 C++ 中读取/写入设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6525812/