Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can set the non-blocking flag (<code>O_NONBLOCK</code>) on the file descriptor using <code>fcntl()</code> to keep <code>read()</code> from waiting for data, but if you do that, you have to continuously poll looking for data, which is obviously bad from a CPU usage standpoint. As Charlie Burns' answer explains, the best solution is to use <code>select()</code> which will allow your program to efficiently wait until there is some data to be read on the port's file descriptor. Here's some example code taken from my own Objective-C serial port class, <a href="https://github.com/armadsen/ORSSerialPort" rel="nofollow">ORSSerialPort</a> (slightly modified):</p> <pre><code>fd_set localReadFDSet; FD_ZERO(&amp;localReadFDSet); FD_SET(self.fileDescriptor, &amp;localReadFDSet); timeout.tv_sec = 0; timeout.tv_usec = 100000; // Check to see if port closed every 100ms result = select(localPortFD+1, &amp;localReadFDSet, NULL, NULL, &amp;timeout); if (!self.isOpen) break; // Port closed while select call was waiting if (result &lt; 0) { // Handle error } if (result == 0 || !FD_ISSET(localPortFD, &amp;localReadFDSet)) continue; // Data is available char buf[1024]; long lengthRead = read(localPortFD, buf, sizeof(buf)); NSData *readData = nil; if (lengthRead&gt;0) readData = [NSData dataWithBytes:buf length:lengthRead]; </code></pre> <p>Note that <code>select()</code> indicates that data is available by returning. So, your program will sit suspended at the <code>select()</code> call while no data is available. The program is <em>not</em> hung, that's how it's supposed to work. If you need to do other things while <code>select()</code> is waiting, you should put the <code>select()</code> call on a different queue/thread from the other work you need to do. <code>ORSSerialPort</code> does this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload