Example: I/O Redirection Using an Anonymous Pipe
Chapter 6.The location of WriteFile in Program2 on the right side of Figure 11-1 assumes that the program reads a large amount of data, processes it, and then writes out results. Alternatively, the write could be inside the loop, putting out results after each read.
Figure 11-1. Process-to-Process Communication Using an Anonymous Pipe
[View full size image]

$ pipe Program1 arguments = Program2 arguments
In UNIX or the Windows command prompt, the corresponding command would be:
$ Program1 arguments | Program2 arguments
Program 11-1. pipe: Interprocess Communication with Anonymous Pipes
#include "EvryThng.h"
int _tmain (int argc, LPTSTR argv [])
/* Pipe together two programs on the command line:
pipe command1 = command2 */
{
DWORD i = 0;
HANDLE hReadPipe, hWritePipe;
TCHAR Command1 [MAX_PATH];
SECURITY_ATTRIBUTES PipeSA = /* For inheritable handles. */
{sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
PROCESS_INFORMATION ProcInfo1, ProcInfo2;
STARTUPINFO StartInfoCh1, StartInfoCh2;
LPTSTR targv = SkipArg (GetCommandLine ());
GetStartupInfo (&StartInfoCh1);
GetStartupInfo (&StartInfoCh2);
/* Find the = separating the two commands. */
while (*targv != '=' && *targv != '\0') {
Command1 [i] = *targv;
targv++;
i++;
}
Command1 [i] = '\0';
/* Skip to start of second command. */
targv = SkipArg (targv);
CreatePipe (&hReadPipe, &hWritePipe, &PipeSA, 0);
/* Redirect standard output & create first process. */
StartInfoCh1.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
StartInfoCh1.hStdError = GetStdHandle (STD_ERROR_HANDLE);
StartInfoCh1.hStdOutput = hWritePipe;
StartInfoCh1.dwFlags = STARTF_USESTDHANDLES;
CreateProcess (NULL, (LPTSTR)Command1, NULL, NULL,
TRUE /* Inherit handles. */, 0, NULL, NULL,
&StartInfoCh1, &ProcInfo1);
CloseHandle (ProcInfo1.hThread);
/* Close the pipe's write handle as it is no longer needed
and to ensure the second command detects a file end. */
CloseHandle (hWritePipe);
/* Repeat (symmetrically) for the second process. */
StartInfoCh2.hStdInput = hReadPipe;
StartInfoCh2.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
StartInfoCh2.hStdError = GetStdHandle (STD_ERROR_HANDLE);
StartInfoCh2.dwFlags = STARTF_USESTDHANDLES;
CreateProcess (NULL, (LPTSTR) targv, NULL, NULL, TRUE, 0, NULL,
NULL, &StartInfoCh2, &ProcInfo2);
CloseHandle (ProcInfo2.hThread);
CloseHandle (hReadPipe);
/* Wait for the first and second processes to terminate. */
WaitForSingleObject (ProcInfo1.hProcess, INFINITE);
CloseHandle (ProcInfo1.hProcess);
WaitForSingleObject (ProcInfo2.hProcess, INFINITE);
CloseHandle (ProcInfo2.hProcess);
return 0;
}
