c++ 进程间通信(管道和共享内存分别写),给个简单代码,包注释
1个回答
展开全部
#include <stdio.h>
#include <windows.h>
int main(int argc, char* argv[])
{
if (argv[1] == 0) { //如果是主进程
HANDLE hPipeW, hPipeR; //读管道和写管道
STARTUPINFOA si;
PROCESS_INFORMATION pi;
char str[128];
char param[1024];
CreatePipe(&hPipeR, &hPipeW, NULL, 0);
SetHandleInformation(hPipeW, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); //使得子进程可以继承这个句柄
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
sprintf(param, "\"%s\" %x", argv[0], hPipeW); //传给子进程的参数
if (CreateProcessA(argv[0], param, 0, 0, TRUE, 0, 0, 0, &si, &pi) != FALSE) {
char* pstr = str;
CloseHandle(hPipeW); //关闭管道的输入端,因为此时已经由子进程使用输入端了
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
for(;;) {
DWORD r;
ReadFile(hPipeR, pstr, 128, &r, 0); //从管道读取数据
if (r > 0)
pstr += r;
else
break;
}
CloseHandle(hPipeR);
puts(str);
}
return 0;
} else { //如果是子进程
char str[] = "Hello!";
HANDLE hPipeW;
DWORD r;
sscanf(argv[1], "%x", &hPipeW); //从参数获取管道的写句柄
WriteFile(hPipeW, str, sizeof(str), &r, 0); //往管道写入数据
CloseHandle(hPipeW);
return 0;
}
}
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main(int argc, char* argv[])
{
if (argv[1] == 0) { //如果是作为主进程运行
HANDLE hShmem;
char param[1024];
STARTUPINFOA si;
PROCESS_INFORMATION pi;
char* pstr;
hShmem = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, 256, 0); //创建共享内存对象
SetHandleInformation(hShmem, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); //使得句柄可以继承到子进程
sprintf(param, "\"%s\" %x", argv[0], hShmem);
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
CreateProcessA(argv[0], param, 0, 0, TRUE, 0, 0, 0, &si, &pi);
WaitForSingleObject(pi.hProcess, INFINITE); //等待子进程运行结束
pstr = (char*) MapViewOfFile(hShmem, FILE_MAP_WRITE, 0, 0, 0); //将共享内存对象中的内存块映射到当前进程
puts(pstr);
UnmapViewOfFile(pstr);
CloseHandle(hShmem);
return 0;
} else { //如果是作为子进程运行
HANDLE hShmem;
char* pstr;
sscanf(argv[1], "%x", &hShmem);
pstr = (char*) MapViewOfFile(hShmem, FILE_MAP_WRITE, 0, 0, 0); //将共享内存对象中的对象映射到当前进程
strcpy(pstr, "Hello~!"); //往共享内存里写入字符串
UnmapViewOfFile(hShmem);
CloseHandle(hShmem);
return 0;
}
}
大雅新科技有限公司
2024-11-19 广告
2024-11-19 广告
这方面更多更全面的信息其实可以找下大雅新。深圳市大雅新科技有限公司从事KVM延长器,DVI延长器,USB延长器,键盘鼠标延长器,双绞线视频传输器,VGA视频双绞线传输器,VGA延长器,VGA视频延长器,DVI KVM 切换器等,优质供应商,...
点击进入详情页
本回答由大雅新科技有限公司提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询