/ Published in: C
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <iostream> #include <windows.h> #include <assert.h> using namespace std; HANDLE g_hCom = INVALID_HANDLE_VALUE; const unsigned MAX_BUF_LEN = 32; const char* const g_pData = "hello"; DWORD WINAPI ThreadRead( LPVOID lpParameter ) { char szBuf[ MAX_BUF_LEN ] = { 0 }; DWORD dwRead; OVERLAPPED ov; ov.hEvent = CreateEvent( NULL, TRUE, TRUE, NULL ); { if( GetLastError() != ERROR_IO_PENDING ) { cout << "Read com failed." << endl; return 0; } WaitForSingleObject( ov.hEvent, INFINITE ); GetOverlappedResult( g_hCom, &ov, &dwRead, TRUE ); } { cout << "Failed to get all the data." << endl; return 0; } cout << "Read: " << szBuf << endl; return 1; } int main() { g_hCom = CreateFile( "com1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL ); HANDLE hThread = CreateThread( NULL, 0, ThreadRead, NULL, 0, NULL ); Sleep( 100 ); DWORD dwWritten; OVERLAPPED ov; ov.hEvent = CreateEvent( NULL, TRUE, TRUE, NULL ); { if( GetLastError() != ERROR_IO_PENDING ) { cout << "Write com failed." << endl; return 0; } WaitForSingleObject( ov.hEvent, INFINITE ); GetOverlappedResult( g_hCom, &ov, &dwWritten, TRUE ); } { cout << "Failed to write all the data." << endl; return 0; } cout << "Write: " << g_pData << endl; Sleep( 100 ); return 1; }