用C ++读/写设备 [英] Read/write into a device in C++

查看:52
本文介绍了用C ++读/写设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中读取/写入设备?该设备位于/dev/ttyPA1 中.
我考虑过fstream,但我不知道该设备是否具有可以在不阻止该应用程序的情况下读取的输出.
我的目标是创建和应用程序,在其中将某些内容写入终端,然后将其发送到/dev/ttyPA1 中.如果设备有回写功能,它将从设备读取内容并写入屏幕.如果不是,它将提示用户再次写入设备.
我该怎么办?

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?

推荐答案

使用 open(2) read(2) write(2) 进行读取并写入设备(并且不要忘记 close(2)完成后).您还可以使用C stdio函数( fopen(3) 和朋友)或C ++ fstream类,但是如果这样做,您几乎肯定要禁用缓冲( setvbuf(3) 用于stdio,或 outFile.rdbuf()-> pubsetbuf(0,0)用于fstreams).

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).

这些都将在 blocking 模式下运行.您可以使用 select(2) 来测试是否可能在没有阻塞的情况下读取或写入文件描述符(如果不可能的话,则不应这样做).或者,您可以使用 O_NONBLOCK 标志打开文件(或使用 fcntl(2) (在打开后设置标志)在文件描述符上使其不阻塞;然后,对 read(2) write(2)的任何调用都将阻塞,而调用立即失败,并显示错误 EWOULDBLOCK .

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.

例如:

// 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 ++读/写设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆