C++代码:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
while(1)
{
// 创建管道服务器
char strPipeName[] = "\\\\.\\pipe\\tongxun";// \\\\.\\pipe\\ = IPC通信共享内存文件目录 tongxun = 命名名称
char szBuf[1024] = {0};
DWORD dwRead ;
//DWORD userID;
//char cmd;
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;
}
cout <<"创建 ------------------------------" <<endl;
// 连接管道,持续等待,直到有客户链接成功
if(ConnectNamedPipe(hIPC, NULL)){
cout <<"链接 √" <<endl;
}else{
cout <<"链接 ×" <<endl;
}
// 从管道读取信息,持续等待,直到客户写入数据
if (!ReadFile(hIPC, szBuf, sizeof(szBuf), &dwRead, 0))
{
cout <<"未读取到数据" <<endl;
break;
}
//处理读到的数据szBuf...
cout << "读: "<< szBuf <<endl;
//写数据...
char msg[] = "C++服务端写入的内容";
if(WriteFile(hIPC, msg, strlen(msg), &dwRead, NULL)){
cout << "写 √"<<endl;
}else{
cout << "写 ×"<<endl;
}
// Sleep(100);
CloseHandle(hIPC);
}
return 0;
}
PHP代码:
<?php
echo Pipe("PHP 写入的数据");
function Pipe($msg)
{
$fp = @fopen("\\\\.\\pipe\\tongxun", 'w+r+b'); // \\\\.\\pipe\\ = IPC通信共享内存文件目录 tongxun = 命名名称
@fwrite($fp,$msg);//写
$result = @fread($fp,100);//读
return $result ;
fclose($fp);
}
?>