title: Reading and writing to/from serial device via USB on Linux with perl or PHP
body: <p>I'm having a problem reading from a serial device on Linux. The problem is rather weird, and I wasn't able to nail down the causes.</p>
  
  <p>I'm opening the <code>/dev/ttyUSB0 file</code> with PHP and beginning to communicate with the device according to the device's protocol. Many times I encountered a situation where the PHP script waits for the device to respond. When I ran a Perl script in parallel which supposed to do the same it sent a request to the same device, and quit supposedly without getting a response. Then I saw that the PHP script got the response (only after the Perl script sent a request).</p>
  
  <p>I encountered a similar matter when trying to read Arduino with PHP. The PHP got no response from the port, but Arduino IDE's Serial Monitor printed it.</p>
  
  <p>I think I'm missing a crucial thing about Linux files and USB ports here. What might be the problem? How can I tell which programs use the port/file?</p>
  
  <pre><code>    $usb = 'ttyUSB0';        
      `stty -F /dev/$usb 9600`;
      `stty -F /dev/$usb -parity`;
      `stty -F /dev/$usb cs8`;
      `stty -F /dev/$usb -cstopb`;
      $f = fopen("/dev/$usb", "r+");
      if(!$f) {
          echo "error opening file\n";
          exit;
      }
  
      statusRequest($f);
      sleep(1);
      $c = readPort($f);
      echo "$c\n";
  
  function statusRequest($port) {
      $data = "request";
      fwrite($port, $data);
      fflush($port);
  }
  
  function readPort($port) {
      $read = 1;
      $c = '';
      while($read &gt; 0) {
          $bytesr = unpack("h*", fread($port, 1));
          $c .= $bytesr[1];
          //echo $bytesr[1];
          if($bytesr[1] == 'ff') {
              $read = 0;
          }
      }    
      return $c;
  }
  </code></pre>