win32 - 匿名管道的使用
目标: 创建一个父进程和子进程,在子进程的控制台窗口输入数据,数据通过管道发送给父进程,父进程的控制台窗口读取数据,最后将数据打印出来。
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 - 匿名管道的使用的更多相关文章
- Linux学习笔记(12)-进程间通信|匿名管道
Linux的进程间通信有几种方式,包括,管道,信号,信号灯,共享内存,消息队列和套接字等-- 现在一个个的开始学习! ----------------------------------------- ...
- Linux进程间通信(三):匿名管道 popen()、pclose()、pipe()、close()、dup()、dup2()
在前面,介绍了一种进程间的通信方式:使用信号,我们创建通知事件,并通过它引起响应,但传递的信息只是一个信号值.这里将介绍另一种进程间通信的方式——匿名管道,通过它进程间可以交换更多有用的数据. 一.什 ...
- linux进程通信之使用匿名管道进行父子进程通信
管道:是指用于连接一个读进程和一个写进程,以实现它们之间通信的共享文件,又称pipe文件. 管道是单向的.先进先出的.无结构的.固定大小的字节流,它把一个进程的标准输出和另一个进程的标准输入连接在一起 ...
- [C++] socket -9[匿名管道]
::怎么弄都不能读取信息....先把代码放着.... #include<windows.h> #include<stdio.h> int main() { HANDLE rea ...
- 匿名管道读取CMD回显信息
之前用了很坑爹的做法去读取了cmd命令的回显信息,现在发现了用匿名管道的实现方法,由于楼主没有学过Windows核心编程,找了一个代码来凑数 存下来以后研究 #include <windows. ...
- Windows下 C++ 实现匿名管道的读写操作
由于刚弄C++没多久,部分还不熟练,最近又由于开发需求要求实现与其他程序进行通信,瞬间就感觉想到了匿名通信.于是自己查阅了一下资料,实现了一个可读可写的匿名管道: 源代码大部分都有注释: Pipe.h ...
- Linux进程间通信-匿名管道
前面我们讲了进程间通信的一种方式,共享内存.下面看一看另一种机制,匿名管道.1.什么是管道管道是一个进程的数据流到另一个进程的通道,即一个进程的数据输出作为另一个进程的数据输入,管道起到了桥梁的作用. ...
- IPC——匿名管道
Linux进程间通信——使用匿名管道 在前面,介绍了一种进程间的通信方式:使用信号,我们创建通知事件,并通过它引起响应,但传递的信息只是一个信号值.这里将介绍另一种进程间通信的方式——匿名管道,通过它 ...
- 使用匿名管道在进程间通信 (System.IO.Pipes使用)(转)
原文地址:http://www.cnblogs.com/yukaizhao/archive/2011/08/04/system-io-pipes.html 管道的用途是在同一台机器上的进程之间通信,也 ...
- Linux进程通信----匿名管道
Linux进程通信中最为简单的方式是匿名管道 匿名管道的创建需要用到pipe函数,pipe函数参数为一个数组表示的文件描述字.这个数组有两个文件描 述字,第一个是用于读数据的文件描述符第二个是用于写数 ...
随机推荐
- [转贴]loadrunner 场景设计-添加Unix、Linux Resources计数器
loadrunner 场景设计-添加Unix.Linux Resources计数器 https://www.cnblogs.com/shouke/p/10158239.html 场景设计-添加Un ...
- echasrts定义折线图legend的样式-优化
option = { title: { text: '折线图堆叠' }, tooltip: { trigger: 'axis' }, //定义折线图legend的形状哈 legend: { itemW ...
- HUBUCTF 2022新生赛Writeup
既然是母校,那一定要好好对待~ 2024-01-13 22:42:34 WEB [HUBUCTF 2022 新生赛]checkin 题目链接:checkin 原题 <?php show_ ...
- SqlSugar联表查询
Join用法 语法糖1.2和3 在Where OrderBy GroupBy Select用法都一样的,他们区别就在JOIN的方式不一样,其它都一样 语法糖1 优点:好理解,5个表以内的联表非常爽,支 ...
- 多模态对比语言图像预训练CLIP:打破语言与视觉的界限
多模态对比语言图像预训练CLIP:打破语言与视觉的界限 一种基于多模态(图像.文本)对比训练的神经网络.它可以在给定图像的情况下,使用自然语言来预测最相关的文本片段,而无需为特定任务进行优化.CLIP ...
- Flask 框架:运用SocketIO实现WebSSH
Flask 框架中如果想要实现WebSocket功能有许多种方式,运用SocketIO库来实现无疑是最简单的一种方式,Flask中封装了一个flask_socketio库该库可以直接通过pip仓库安装 ...
- vue-router.esm.js:2065 Uncaught (in promise) Error: Redirected when going from "/login?redirect=%2Fhome" to "/home" via a navigation guard.
原因: vue-router路由版本更新产生的问题,导致路由跳转失败抛出该错误; 真正的原因是由于返回了一个Promise对象, 正常的跳转由then方法执行 当正常的路由跳转, 被"路 ...
- powerDesigner 逆向工程 mysql 生成 PDM
1. 信息补充说明 powerDesigner 16.5 mysql 5.6 主要内容:使用powerDesigner的逆向工程,将mysql中的数据库转换成PDM文件 所需资源: powerDe ...
- PHP的数据对象PDO
PHP的数据对象PDO 一.什么是PDO 手册说:PHP 数据对象 (PHP Data Object) 扩展为PHP访问数据库定义了一个轻量级的一致接口.实现 PDO 接口的每个数据库驱动可以公开具体 ...
- 手把手带你上手swagger3
配置POM 只需要加一个依赖,并且要注意,swagger3在springboot2.5版本以上会出现问题 <dependency> <groupId>io.springfox& ...