管道是一种用于在进程间共享数据的机制,其实质是一段共享内存.
Windows系统为这段共享的内存设计采用数据流I/0的方式来访问.
命令管道可以在任意进程间通信,通信是双向的,任意一端都可读可写,但是在同一时间只能有一端读,一端写.
Note:须包含头文件 #include <windows.h>
一、父进程
//
// 1.Create pipe
//
HANDLE hReadPipe;
HANDLE hWritePipe;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
BOOL flag;
flag = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
if (flag)
{
// CreatePipe successfully.
......
}
else
{
// CreatePipe failed.To get extended error information, call GetLastError.
......
}
//
// 2.Create child process
//
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = hReadPipe;
si.hStdOutput = hWritePipe;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
ZeroMemory(&pi, sizeof(pi));
TCHAR szCommandLine[] = TEXT("child.exe");
if(!CreateProcess(
NULL, // No module name (use command line)
szCommandLine, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
TRUE, // Set handle inheritance to TRUE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
// CreateProcess successfully.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
// CreateProcess failed.
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
hReadPipe = NULL;
hWritePipe = NULL;
......
}
//
// 3.Read File
//
char buf[100] = { 0 };
DWORD dwBytesRead;
if(!ReadFile(hReadPipe, buf, 100, &dwBytesRead, NULL))
{
// ReadFile failed.
......
}
else
{
// ReadFile successfully.
......
}
//
// 4.Write File
//
char buf[] = "Hello Kitty.";
DWORD dwBytesWritten;
if(!WriteFile(hWritePipe, buf, sizeof(buf), &dwBytesWritten, NULL))
{
// Write file failed.
}
else
{
// Write file successfully.
}
二、子进程
//
// 1.获取句柄
//
HANDLE hReadPipe;
HANDLE hWritePipe;
hReadPipe = GetStdHandle(STD_INPUT_HANDLE);
hWritePipe = GetStdHandle(STD_OUTPUT_HANDLE);
//
// 2.Read File
//
char buf[100] = { 0 };
DWORD dwBytesRead;
if(!ReadFile(hReadPipe, buf, 100, &dwBytesRead, NULL))
{
// ReadFile failed.
......
}
else
{
// ReadFile successfully.
......
}
//
// 3.Write File
//
char buf[] = "Hello Kitty.";
DWORD dwBytesWritten;
if(!WriteFile(hWritePipe, buf, sizeof(buf), &dwBytesWritten, NULL))
{
// Write file failed.
}
else
{
// Write file successfully.
}