tags:

views:

516

answers:

3
A: 

Use a select statement, which will check the read and write buffers without blocking and return their status, so you only need to read when you know the port has data, or write when you know there's room in the output buffer.

The third example at http://www.developerweb.net/forum/showthread.php?t=2933 and the associated comments may be helpful.

Edit: The man page for select has a simpler and more complete example near the end. You can find it at http://linux.die.net/man/2/select if man 2 select doesn't work on your system.

Note: Mastering select() will allow you to work with both serial ports and sockets; it's at the heart of many network clients and servers.

Adam Liss
Can I see an example of the select statement being used or a link to an example? I couldn't find it on google.
Steve
Adam Liss
select() only works with POSIX file descriptors (integers), NOT Windows HANDLEs.
Adam Rosenfield
A: 

For a Windows environment the more native approach would be to use asynchronous I/O. In this mode you still use calls to ReadFile and WriteFile, but instead of blocking you pass in a callback function that will be invoked when the operation completes.

It is fairly tricky to get all the details right though.

Rob Walker
The trouble with asynch Serial I/O is that the first byte you get is going to trigger your data-read event, after which you have to somehow figure out when you're done getting new data. I think I'm going to ask a question about that, since there doesn't seem to be a good answer yet
Coderer
We typically either (1) read until the buffer is empty, assuming there *is* a buffer, or (2) stay in the read loop until an appropriate timeout occurs. "Appropriate" is left as an exercise for the reader. :-)
Adam Liss
A: 

Here is a copy of an article that was published in the c/C++ users journal a few years ago. It goes into detail on the Win32 API.

simon