目标: 创建一个父进程和子进程,在子进程的控制台窗口输入数据,数据通过管道发送给父进程,父进程的控制台窗口读取数据,最后将数据打印出来。

Parent.cpp

//CMD.exe
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h> #define BUFSIZE 4096 HANDLE g_hChildStd_Rd = NULL;
HANDLE g_hChildStd_Wr = NULL; HANDLE g_hInputFile = NULL; void CreateChildProcess(void);
void ReadFromPipe(void);
void ErrorExit(LPCWSTR); int _tmain(int argc, TCHAR* argv[])
{
SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&g_hChildStd_Rd, &g_hChildStd_Wr, &saAttr, 0))
ErrorExit(L"StdoutRd CreatePipe"); // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(g_hChildStd_Rd, HANDLE_FLAG_INHERIT, 0))
ErrorExit(L"Stdout SetHandleInformation"); CreateChildProcess(); // Read from pipe that is the standard output for child process. printf("\n->Contents of child process STDOUT:\n\n");
ReadFromPipe(); printf("\n->End of parent execution.\n"); return 0;
} void CreateChildProcess()
{
TCHAR szCmdline[] = TEXT("Child.exe");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE; // Set up members of the PROCESS_INFORMATION structure. ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_Wr;
siStartInfo.hStdOutput = g_hChildStd_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES; // Create the child process. bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NEW_CONSOLE, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION // If an error occurs, exit the application.
if (!bSuccess)
ErrorExit(L"CreateProcess");
else
{
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread); CloseHandle(g_hChildStd_Wr);
}
} void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE); for (;;)
{
bSuccess = ReadFile(g_hChildStd_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if (!bSuccess || dwRead == 0) break; bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (!bSuccess) break;
}
} void ErrorExit(LPCWSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError(); FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL); lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}

Child.cpp

#include <windows.h>
#include <stdio.h> #define BUFSIZE 4096
#pragma warning(disable:4996) int main(void)
{
CHAR chBuf[BUFSIZE] = {};
DWORD dwRead, dwWritten;
HANDLE hStdin, hStdout;
BOOL bSuccess; hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (
(hStdout == INVALID_HANDLE_VALUE) ||
(hStdin == INVALID_HANDLE_VALUE)
)
ExitProcess(1); // Send something to this process's stdout using printf.
printf("\n ** This is child process. ** \n"); // This simple algorithm uses the existence of the pipes to control execution.
// It relies on the pipe buffers to ensure that no data is lost.
// Larger applications would use more advanced process control. for (;;)
{
ReadFile(hStdin, chBuf, strlen(chBuf) + 2, &dwRead, NULL);
// Write to standard output and stop on error.
bSuccess = WriteFile(hStdout, chBuf, strlen(chBuf)+2, &dwWritten, NULL);
memset(chBuf, NULL, BUFSIZE);
if (!bSuccess)
break;
}
return 0;
}

效果:

win32 - 匿名管道的使用的更多相关文章

  1. Linux学习笔记(12)-进程间通信|匿名管道

    Linux的进程间通信有几种方式,包括,管道,信号,信号灯,共享内存,消息队列和套接字等-- 现在一个个的开始学习! ----------------------------------------- ...

  2. Linux进程间通信(三):匿名管道 popen()、pclose()、pipe()、close()、dup()、dup2()

    在前面,介绍了一种进程间的通信方式:使用信号,我们创建通知事件,并通过它引起响应,但传递的信息只是一个信号值.这里将介绍另一种进程间通信的方式——匿名管道,通过它进程间可以交换更多有用的数据. 一.什 ...

  3. linux进程通信之使用匿名管道进行父子进程通信

    管道:是指用于连接一个读进程和一个写进程,以实现它们之间通信的共享文件,又称pipe文件. 管道是单向的.先进先出的.无结构的.固定大小的字节流,它把一个进程的标准输出和另一个进程的标准输入连接在一起 ...

  4. [C++] socket -9[匿名管道]

    ::怎么弄都不能读取信息....先把代码放着.... #include<windows.h> #include<stdio.h> int main() { HANDLE rea ...

  5. 匿名管道读取CMD回显信息

    之前用了很坑爹的做法去读取了cmd命令的回显信息,现在发现了用匿名管道的实现方法,由于楼主没有学过Windows核心编程,找了一个代码来凑数 存下来以后研究 #include <windows. ...

  6. Windows下 C++ 实现匿名管道的读写操作

    由于刚弄C++没多久,部分还不熟练,最近又由于开发需求要求实现与其他程序进行通信,瞬间就感觉想到了匿名通信.于是自己查阅了一下资料,实现了一个可读可写的匿名管道: 源代码大部分都有注释: Pipe.h ...

  7. Linux进程间通信-匿名管道

    前面我们讲了进程间通信的一种方式,共享内存.下面看一看另一种机制,匿名管道.1.什么是管道管道是一个进程的数据流到另一个进程的通道,即一个进程的数据输出作为另一个进程的数据输入,管道起到了桥梁的作用. ...

  8. IPC——匿名管道

    Linux进程间通信——使用匿名管道 在前面,介绍了一种进程间的通信方式:使用信号,我们创建通知事件,并通过它引起响应,但传递的信息只是一个信号值.这里将介绍另一种进程间通信的方式——匿名管道,通过它 ...

  9. 使用匿名管道在进程间通信 (System.IO.Pipes使用)(转)

    原文地址:http://www.cnblogs.com/yukaizhao/archive/2011/08/04/system-io-pipes.html 管道的用途是在同一台机器上的进程之间通信,也 ...

  10. Linux进程通信----匿名管道

    Linux进程通信中最为简单的方式是匿名管道 匿名管道的创建需要用到pipe函数,pipe函数参数为一个数组表示的文件描述字.这个数组有两个文件描 述字,第一个是用于读数据的文件描述符第二个是用于写数 ...

随机推荐

  1. ext4 磁盘扩容

    目录 ext4文件系统磁盘扩容 目标 途径 操作步骤 改变前的现状 操作和改变后的状态 ext4文件系统磁盘扩容 一个磁盘有多个分区,分别创建了物理卷.卷组.逻辑卷.通过虚拟机软件对虚拟机的磁盘/de ...

  2. [转帖]Rust在windows下安装以后cargo build Error: linker `link.exe` not found

    D:\rust\runoob-greeting\greeting>cargo build error: linker `link.exe` not found | = note: 系统找不到指定 ...

  3. Find 查找并且展示最近24小时内创建的文件信息

    1. 命令为: find /gscloud/tools/patchinstall/patchfiles/ -maxdepth 1 -mtime 1 |cut -c40- >/deploy/pat ...

  4. git有关commit的命令

    2.更改最近一次(本次) commit 的提交信息: 当我们执行 git add . git commit -m "0-0-1" 之后我们发现自己写的提交信息是不符合项目要求的,这 ...

  5. vue全局事件总线和消息订阅详细讲解

    全局事件总线 在写组件的时候,我们都知道父传递子 也知道子传递给父 但是组件间嵌套复杂的时候我们应该怎么通信呢? 有的小伙伴会说适用vuex,的确是可以解决问题的 下面我们说一下全局事件总线 一种组件 ...

  6. 【代码分享】使用 avx2 + 查表法,优化凯撒加密

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 接上一篇:[代码分享]使用 avx512 + 查表法,优化 ...

  7. 【调研】VictoriaMetrics的上报api能否替换prometheus的api?

    prometheus的上报api在:https://github.com/prometheus/client_golang VictoriasMetrics的上报API在:https://github ...

  8. ABP-VNext 用户权限管理系统实战----问题与解决方案

    1.swagger请求总是报:400 Bad Request,但是postman请求是没有问题 查看日志报表: 解决方案: 在 ConfigureServices 中增加如下的内容 Configure ...

  9. js设计模式(下)

    引用:(23条消息) <Javascript设计模式与开发实践>关于设计模式典型代码的整理(下):模板方法模式.享元模式.职责链模式.中介者模式.装饰模式.状态模式.适配器模式_QQsil ...

  10. TextBrewer:融合并改进了NLP和CV中的多种知识蒸馏技术、提供便捷快速的知识蒸馏框架、提升模型的推理速度,减少内存占用

    TextBrewer:融合并改进了NLP和CV中的多种知识蒸馏技术.提供便捷快速的知识蒸馏框架.提升模型的推理速度,减少内存占用 TextBrewer是一个基于PyTorch的.为实现NLP中的知识蒸 ...