- #include <iostream>
- #include <windows.h>
- #include <assert.h>
- using namespace std;
- #define MAX_BUF_LEN 32
- #define COMM_NO "com1"
- HANDLE g_hCom = INVALID_HANDLE_VALUE;
- const char* const g_pData = "hello";
- DWORD WINAPI ThreadRead( LPVOID lpParameter )
- {
- char szBuffer[ MAX_BUF_LEN ] = { 0 };
- DWORD dwRead;
- if( !ReadFile( g_hCom, szBuffer, strlen( g_pData ), &dwRead, NULL ) )
- {
- cout << "Read com failed." << endl;
- return -1;
- }
- if( dwRead != strlen( g_pData ) )
- {
- cout << "Failed to read all the data." << endl;
- return -1;
- }
- cout << "Read: " << szBuffer << endl;
- return 0;
- }
- int main()
- {
- g_hCom = CreateFile( COMM_NO, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
- assert( g_hCom != INVALID_HANDLE_VALUE );
- HANDLE hThread = CreateThread( NULL, 0, ThreadRead, NULL, 0, NULL );
- assert( hThread != NULL );
- Sleep( 100 );
- DWORD dwWritten;
- if( !WriteFile( g_hCom, g_pData, strlen( g_pData ), &dwWritten, NULL ) )
- {
- cout << "Write com failed." << endl;
- return -1;
- }
- if( dwWritten != strlen( g_pData ) )
- {
- cout << "Failed to write all the data." << endl;
- return -1;
- }
- cout << "Write: " << g_pData << endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/050120131295.html
来源: http://www.codesnippet.cn/detail/050120131295.html