// Server.cpp
#include <windows.h>
#include <cstdio>
int main(int argc, char *argv[])
{
HANDLE hOldStdin, hOldStdout;
// define two variables to record the information of the process to be create
bool isSuccess = false;
STARTUPINFO startInfo;
PROCESS_INFORMATION processInfomation;
// initialize
memset(&startInfo, 0, sizeof(startInfo));
startInfo.cb = sizeof(startInfo);
memset(&processInfomation, 0, sizeof(processInfomation));
// create a anonymous pope to communicate
// between parent process and child process
// handles to indicate the write-point and read-point of the pipe
HANDLE hWritePipe, hReadPipe;
// security attribute for the pipe to be created
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = true;
// get handles of standard console
hOldStdout = GetStdHandle(STD_OUTPUT_HANDLE);
hOldStdin = GetStdHandle(STD_INPUT_HANDLE);
// create a anonymous pipe
CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
// redirect standard console to the pipe
SetStdHandle(STD_OUTPUT_HANDLE, hWritePipe);
SetStdHandle(STD_INPUT_HANDLE, hReadPipe);
// create child process which will write the pipe throug "standard console"
if (!CreateProcess(TEXT("C://Client.exe"),NULL, NULL, NULL, FALSE, 0,
NULL, NULL, &startInfo, &processInfomation)) {
// if fail to create child process
printf("failure to create new process!/n");
DWORD dwErrorNo = GetLastError();
printf("Error No. is %d/n", dwErrorNo);
// close handles of pipe
CloseHandle(hWritePipe);
CloseHandle(hWritePipe);
ExitProcess(1);
}
else {
// close the handle of primary thread of the child process
CloseHandle(processInfomation.hThread);
WaitForSingleObject(processInfomation.hProcess, INFINITE);
// read the result of process through pipe
int rest;
DWORD dwReadedBytes;
memset(&rest, 0, sizeof(rest));
ReadFile(hReadPipe, &rest, sizeof(rest)*8, &dwReadedBytes, NULL);
printf("the sum is %d/n", rest);
// terminate parent process inartificially
return 0;
}
}
// Client.cpp
#include <windows.h>
#include <cstdio>
// the result of function sum will be written into pipe
int sum (int a, int b) {
return a + b;
}
int main(int argc, char *argv[])
{
// get the handle of pipe created by parent process,
// and which is indirected through standard console
HANDLE hPipeWrite = GetStdHandle(STD_OUTPUT_HANDLE);
if (hPipeWrite == INVALID_HANDLE_VALUE) {
printf("Failure to get std output handle, in child process sum!/n");
ExitProcess(1);
}
// call the function sum
int res = sum(10, 20);
// the variable to indicate the length of date to be written into pope
DWORD dwNumByteToWriten = sizeof(res) * 8;
// write the data calculated by the function sum into pipe
if (!WriteFile(hPipeWrite, &res, sizeof(res)*8, &dwNumByteToWriten, NULL)) {
// if fail to write pipe
printf("failure to writen pipe!/n");
ExitProcess(1);
}
else {
// successfully to write pipe
CloseHandle(hPipeWrite);
return 0;
}
}