c++ builder (win32api?) > named pipe > connect


動作環境
C++ Builder XE4

関連 http://qiita.com/7of9/items/2159bbba0dce8bd8add4

vmwareのゲストOSとホストOS間の通信について調査中。

https://msdn.microsoft.com/ja-jp/library/windows/desktop/aa365592.aspx
においてNamed Pipe Clientの実装例が見つかった。

コードはおそらくwin32apiなのかと思う(よく分かっていない)。

C++ Builder XE4上でconnectまで実装してみた。

code

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <windows.h>
//#include <conio.h>
#include <tchar.h>

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------

#define BUFSIZE (512)


__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    HANDLE hPipe;
    LPTSTR lpvMessage=TEXT("Default message from client.");
    TCHAR  chBuf[BUFSIZE];
    BOOL   fSuccess = FALSE;
    DWORD  cbRead, cbToWrite, cbWritten, dwMode;
    LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\com_1");

    while(1)
    {
      hPipe = CreateFile(
         lpszPipename,   // pipe name
         GENERIC_READ |  // read and write access
         GENERIC_WRITE,
         0,              // no sharing
         NULL,           // default security attributes
         OPEN_EXISTING,  // opens existing pipe
         0,              // default attributes
         NULL);          // no template file

        // Break if the pipe handle is valid.
        if (hPipe != INVALID_HANDLE_VALUE) {
            break;
        }

        if (GetLastError() != ERROR_PIPE_BUSY) {
            String msg = String().sprintf(L"Could not open pipe. GLE=%d\n", GetLastError());
            Memo1->Lines->Add(msg);
            return; // error
        }

        if (! WaitNamedPipe(lpszPipename, 20000)) {
            Memo1->Lines->Add(L"Could not open pipe: 20 second wait timed out.");
            return; // error
        }
    }

    Memo1->Lines->Add(L"Connected");
}
//---------------------------------------------------------------------------

実行

vmwareのゲストOSを起動。 named pipeサーバーとしている。
named pipeは"\\.\pipe\com_1"。

ホストOS上にて上記をビルドしたソフトを実行し、Memo1に"Connected"が表示されることを確認した。