title: How can I implement timeout for read() when reading from a serial port (C/C++)
body: <p>I am reading bytes from a serial port in C++ using a file descriptor and the posix/unix read() function. In this example, I am reading 1 byte from the serial port (baud rate settings and similiar are omitted for clarity):</p>
  
  <pre><code>#include &lt;termios.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(void)
  {
     int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
     char buf[1];
     int bytesRead = read(fd, buf, 1);
     close(fd);
     return 0;
  }
  </code></pre>
  
  <p>If the device connected to /dev/ttyS0 does not send any information, the program will hang. How can I set a timeout?</p>
  
  <p>I have tried setting a time out like this:</p>
  
  <pre><code>struct termios options;
  tcgetattr(fd, &amp;options);
  options.c_cc[VMIN] = 0;
  options.c_cc[VTIME] = 10;
  tcsetattr(fd, TCSANOW, &amp;options);
  </code></pre>
  
  <p>I thought it was supposed to give 1 second timeout, but it makes no difference. I think I have misunderstood VMIN and VTIME. What is VMIN and VTIME used for?</p>
  
  <p>Then I searched the web and found somebody talking about the select() function. Is that the solution and if so, how would one apply that to the program above to make 1 second timeout?</p>
  
  <p>Any help is appreciated. Thanks in advance :-)</p>