如何使用线程读写串口数据
我正在创建一个串行端口应用程序,其中我创建两个线程,一个是写入器线程,它将数据写入串行端口,另一个是读取器线程,它将从串行端口读取数据。我知道如何打开、配置、读取和写入数据串行端口,但如何使用线程来做到这一点。
我正在使用 LINUX(ubuntu) 并尝试用 C 语言打开 ttyS0 端口编程。
I am creating a serial port application in which i am creating two threads one is WRITER THREAD which will write data to serial port and a READER THREAD which will read data from serial port.I know how to open, configure,read and write data on serial port but how to do it using threads.
I am using LINUX(ubuntu) and trying to open ttyS0 port programming in C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果只有一个线程读取而其他线程仅写入,则从 2 个线程使用串行端口很简单。
您应该为串行端口使用一个文件描述符。
使用普通的
open
、tcsetattr
等函数在一个线程中打开并初始化它。然后将文件描述符传递给其他线程。
现在,读取器线程可以使用
read()
函数,写入器可以使用write()
函数,而无需任何额外的同步。您还可以在两个线程中使用select()
。关闭文件描述符需要注意,应该在一个线程中完成,以避免出现问题。
Using of a serial port from 2 threads is simple, if only one thread reads and other thread only writes.
You should use one file descriptor for the serial port.
Open and initialize it in one thread by using normal
open
,tcsetattr
, etc functions.Then deliver the file descriptor to the other thread(s).
Now the reader thread can use
read()
function, and the writer can usewrite()
function without any extra synchronization. You can also useselect()
in both threads.Closing of the file descriptor needs attention, you should do it in one thread for avoiding problems.
我过去执行此操作的方法是使用 0 的 VMIN 和 5 十分之一的 VTIME 设置异步 I/O 端口。这样做的目的是让线程注意到应用程序何时关闭,因为它可以尝试读取、超时、检查退出标志,然后尝试读取更多内容。
下面是一个读取函数的示例:
写入函数将如您所期望的那样。
在您的设置功能中,请确保设置:
The way I have done this in the past is to set up the port for asynchronous I/O using a VMIN of 0 and a VTIME of, say, 5 deciseconds. The purpose of this was to allow the thread to notice when it was time for the application to shut down, as it could try to read, time out, check for a quit flag, and then try to read some more.
Here is an example read function:
The write function would look as you would expect.
In your setup function, make sure to set: