I want to write my own application that uses the serial port. I have to read from and write two the port (both at the same time). What’s the best way to do this?
I was thinking about two threads that both do a blocking read or write call. Is this thread safe?
It depends on your application on how you want to organize things (i.e. one or two threads, etc). However, if you want to read to the serial port from Thread A and write in Thread B, I would recommend using non-blocking sockets and use select on the read thread. Be prepared to have to call write or read multiple times if the serial port is in use.
Ok, thanks for your advice.
But I don’t really see the difference between:
- a blocking read()
- a blocking select() followed by a nonblocking read()
Is there a reason why the second method is better?
A blocking read ties up the serial port so you can not write to it. A blocking select returns when there’s data to be read from the serial port. In the case of a blocking read, you must read some data before the call returns, thus if you have another thread (or you don’t want this thread to block) trying to write, calls to write will fail. With a blocking select, you can continue to write to the serial port will you wait for data to arrive on the serial port to be read.
Ok, that’s clear.
Last question: the documentation seems to indicate that select() only works on sockets. But can I use it on any file descriptor?
Category: Socket API Functions
Used to multiplex I/O requests among multiple sockets.
It works with the serial file descriptors. I’m pretty sure you’d have troubles with a normal file description (i.e., to a file) though.
I’m developing with netos 6.3 and I can’t get the serial file descriptor to work correctly with select(). I’m only trying to call select for a receive file descriptor. For the majority of the time, select() is returning after a timeout, but tcgetbuffers() indicates that there is data to be read from the receive buffer. select() is seldom returning after detecting receive data.
I am also facing the same problem. When I use select on the serial port it usually returns after timeout even though there is data present on the serial port. Does anyone have a fix for this problem? I am using netos 7.1