使用 VC 写一个管道的 Demo
时间: 2023-09-07 20:13:40 浏览: 41
以下是一个使用 VC 写的管道的 Demo:
```c++
#include <windows.h>
#include <stdio.h>
#define BUFSIZE 512
int main()
{
HANDLE hReadPipe, hWritePipe;
char buffer[BUFSIZE];
DWORD dwRead, dwWrite;
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) {
printf("CreatePipe failed with error %d\n", GetLastError());
return 1;
}
// 创建一个子进程
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
si.hStdOutput = hWritePipe;
si.dwFlags = STARTF_USESTDHANDLES;
if (!CreateProcess(NULL, "child.exe", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
printf("CreateProcess failed with error %d\n", GetLastError());
return 1;
}
// 父进程从管道中读取数据
while (ReadFile(hReadPipe, buffer, BUFSIZE, &dwRead, NULL) && dwRead > 0) {
buffer[dwRead] = '\0';
printf("Parent: %s", buffer);
}
// 关闭管道和进程句柄
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
```
在上面的代码中,我们使用了 CreatePipe 函数来创建一个管道,并通过 CreateProcess 函数创建了一个子进程。在父进程中,我们通过 ReadFile 函数从管道中读取数据,并将其输出到控制台中。子进程的代码可以在另一个文件中实现,它需要将数据写入管道中。