@@ -57,11 +57,12 @@ void EIO_Open(uv_work_t* req) {
5757 HANDLE file = CreateFile (
5858 data->path ,
5959 GENERIC_READ | GENERIC_WRITE,
60- 0 ,
60+ 0 , // dwShareMode 0 Prevents other processes from opening if they request delete, read, or write access
6161 NULL ,
6262 OPEN_EXISTING,
63- FILE_FLAG_OVERLAPPED,
64- NULL );
63+ FILE_FLAG_OVERLAPPED, // allows for reading and writing at the same time and sets the handle for asynchronous I/O
64+ NULL
65+ );
6566 if (file == INVALID_HANDLE_VALUE) {
6667 DWORD errorCode = GetLastError ();
6768 char temp[100 ];
@@ -368,35 +369,31 @@ void EIO_Write(uv_work_t* req) {
368369 ov.hEvent = CreateEvent (NULL , TRUE , FALSE , NULL );
369370
370371 // Start write operation - synchrounous or asynchronous
371- DWORD bytesWrittenSync = 0 ;
372- if (!WriteFile ((HANDLE)data->fd , data->bufferData , static_cast <DWORD>(data->bufferLength ), &bytesWrittenSync , &ov)) {
372+ DWORD bytesWritten = 0 ;
373+ if (!WriteFile ((HANDLE)data->fd , data->bufferData , static_cast <DWORD>(data->bufferLength ), &bytesWritten , &ov)) {
373374 DWORD lastError = GetLastError ();
374375 if (lastError != ERROR_IO_PENDING) {
375376 // Write operation error
376377 ErrorCodeToString (" Writing to COM port (WriteFile)" , lastError, data->errorString );
378+ CloseHandle (ov.hEvent );
377379 return ;
378- } else {
379- // Write operation is asynchronous and is pending
380- // We MUST wait for operation completion before deallocation of OVERLAPPED struct
381- // or write data buffer
382-
383- // Wait for async write operation completion or timeout
384- DWORD bytesWrittenAsync = 0 ;
385- if (!GetOverlappedResult ((HANDLE)data->fd , &ov, &bytesWrittenAsync, TRUE )) {
386- // Write operation error
387- DWORD lastError = GetLastError ();
388- ErrorCodeToString (" Writing to COM port (GetOverlappedResult)" , lastError, data->errorString );
389- return ;
390- } else {
391- // Write operation completed asynchronously
392- data->result = bytesWrittenAsync;
393- }
394380 }
395- } else {
396- // Write operation completed synchronously
397- data->result = bytesWrittenSync;
398- }
381+ // Write operation is completing asynchronously
382+ // We MUST wait for the operation completion before deallocation of OVERLAPPED struct
383+ // or write data buffer
399384
385+ // block for async write operation completion
386+ bytesWritten = 0 ;
387+ if (!GetOverlappedResult ((HANDLE)data->fd , &ov, &bytesWritten, TRUE )) {
388+ // Write operation error
389+ DWORD lastError = GetLastError ();
390+ ErrorCodeToString (" Writing to COM port (GetOverlappedResult)" , lastError, data->errorString );
391+ CloseHandle (ov.hEvent );
392+ return ;
393+ }
394+ }
395+ // Write operation completed synchronously
396+ data->result = bytesWritten;
400397 data->offset += data->result ;
401398 CloseHandle (ov.hEvent );
402399 } while (data->bufferLength > data->offset );
0 commit comments