程序間通訊-匿名管道用戶端與伺服器端-示範代碼
用戶端
// PipeClientSample.cpp : 定義控制台應用程式的入口點。
//txwtech
#include "stdafx.h"
//#include <iostream.h>
#include <iostream>
using namespace std;
int main()
{
cout<< "這裡是pipeClientSample的标準輸出\r\n" << endl;
cerr << "這裡是pipeClientSample的錯誤輸出111\r\n" << endl;
//system("pause");
return 0;//
}
伺服器端
void CPipeServerSampleDlg::OnBnClickedButtonConnect()
{
// TODO: 在此添加控件通知處理程式代碼
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead, &hWrite, &sa, 0))
{
//m_Log = "調用CreateProcess建立程序失敗";
m_Log = "調用CreatePipe函數建立匿名管道失敗";
UpdateData(FALSE);
return;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
//si.hStdInput = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//if (!CreateProcess(NULL, "PipeClientSample", NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
if (!CreateProcess(NULL, "PipeClientSample", NULL// PipeClientSample.exe在項目的相同檔案夾下面
, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
{
m_Log = "調用CreateProcess建立程序失敗";//PipeClientSample.exe沒有在項目的相同檔案夾下面,就會失敗
UpdateData(FALSE);
return;
}
CloseHandle(hWrite);
char buffer[4096] = { 0 };
DWORD dwByteReads;
while (true)
{
if (ReadFile(hRead, buffer, 4095, &dwByteReads, NULL) == NULL)
break;
m_Log += buffer;
UpdateData(FALSE);
Sleep(1000);
}
}