您的位置:首页 > 其它

windows下IPC的命名管道例子

2009-08-08 22:01 337 查看
客户端源码

#include <windows.h>
#include <iostream>
using namespace std;
const TCHAR szPipeName[] = L"////hello//pipe//lvbin";
int main(void)
{
HANDLE hPipe = CreateFile(szPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hPipe == INVALID_HANDLE_VALUE)
{
printf("CreateFile return [%d]!/n", GetLastError());
return -1;
}
DWORD dwRead, dwWrite;
char szBuf[1024] = {0};

for (int i = 0; i < 10; ++i)
{
sprintf(szBuf, "%d", i);
WriteFile(hPipe, szBuf, strlen(szBuf), &dwWrite, 0);
printf("Send %s/n", szBuf);
memset(szBuf, 0, sizeof(szBuf));
ReadFile(hPipe, szBuf, sizeof(szBuf), &dwRead, 0);
printf("Recv %s/n", szBuf);
}
}


服务器端源码

#include <iostream>
#include <Windows.h>
using namespace std;

int main(void)
{
TCHAR strPipeName[] = L"////.//pipe//lvbin";
PSECURITY_DESCRIPTOR psd;
psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION))
{
LocalFree((HLOCAL)psd);
return -1;
}
if (!SetSecurityDescriptorDacl(psd, TRUE, (PACL)NULL, FALSE))
{
LocalFree((HLOCAL)psd);
return -1;
}
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength =sizeof(SECURITY_ATTRIBUTES);
saAttr.lpSecurityDescriptor = psd;
saAttr.bInheritHandle = TRUE;
HANDLE hIPC = CreateNamedPipe(strPipeName,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1, 0, 0, 1000, &saAttr);
if (hIPC == INVALID_HANDLE_VALUE)
{
return -1;
}
char szBuf[1024] = {0};
DWORD dwRead, dwWrite;
char szWrite[] = "Get You/n";
ConnectNamedPipe(hIPC, NULL);
while(1)
{
if (!ReadFile(hIPC, szBuf, sizeof(szBuf), &dwRead, 0))
{
break;
}
printf("%s/n", szBuf);
memset(szBuf, 0, sizeof(szBuf));

if (!WriteFile(hIPC, szWrite, strlen(szWrite), &dwWrite, NULL))
{
break;
}
}
return 0;
};


很简单的

怕以后找代码麻烦,就贴在这了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: