title: CreateFile not able to share serial (COM) port
body: <p>The <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx" rel="nofollow noreferrer">CreateFile</a> function is useful for opening files or devices for read/write access, providing a handle.</p>
  
  <p>The third parameter, <em>dwShareMode</em>, specifies if the file/device can later be accessed by others. An example, with files:</p>
  
  <pre><code>void* pFileHandle1 = ::CreateFileA("C:\\test.txt", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
  DWORD lastError = GetLastError(); // 0, ERROR_SUCCESS
  void* pFileHandle2 = ::CreateFileA("C:\\test.txt", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
  lastError = GetLastError(); // 0, ERROR_SUCCESS
  </code></pre>
  
  <p>All good here: we have 2 different handles that can read/write a single file.</p>
  
  <p>But in my case, I want to use a COM port:</p>
  
  <pre><code>void* pComHandle1 = ::CreateFileA("\\\\.\\COM3", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
  lastError = GetLastError(); // 0, ERROR_SUCCESS
  void* pComHandle2 = ::CreateFileA("\\\\.\\COM3", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
  lastError = GetLastError(); // 5, ERROR_ACCESS_DENIED Oops!
  </code></pre>
  
  <p>The first handle is valid and can be used, but the second one is INVALID_HANDLE_VALUE.</p>
  
  <p>What's up with that? Can't you share COM ports that way?</p>