15,471
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <stdio.h>
#include <Windows.h>
#include "process.h"
#define THREAD_NUM 2
HANDLE hReadPipe1, hWritePipe1, hReadPipe2, hWritePipe2;
HANDLE handle[THREAD_NUM];
DWORD byteRead, byteWrite;
string write_message;
unsigned int __stdcall ThreadWritePipe(PVOID pData)
{
//进程的输入重定向到hReadPipe2,所以从hWritePipe2写入
while (true)
{
if (!write_message.empty())
{
if (!WriteFile(hWritePipe2, (LPCVOID)write_message.c_str(), write_message.length() + 1, &byteWrite, NULL))
{
return 1;
}
else
{
write_message = "";
}
}
}
return 0;
}
unsigned int __stdcall ThreadReadPipe(PVOID pData)
{
//这个不知道还有没有更好的办法,用while (true)总觉得很土
BYTE buffer[1024];
while(true)
{
RtlZeroMemory(buffer,1024);
//进程的输出重定向到hWritePipe1,所以从hReadPipe1读取
if(ReadFile(hReadPipe1,buffer,1023,&byteRead,NULL) == NULL)
{
break;
}
cout<<buffer;
Sleep(20);
}
return 0;
}
int main(int argc,char* * argv)
{
//定义四个句炳保留两个管道的信息
SECURITY_ATTRIBUTES sat;
STARTUPINFO startupinfo;
PROCESS_INFORMATION pinfo;
string rString;
string m_Host="c:\\windows\\system32\\cmd.exe ";
sat.nLength=sizeof(SECURITY_ATTRIBUTES);
sat.bInheritHandle=true;
sat.lpSecurityDescriptor=NULL;
//创建管道,它用来做子进程的输出
if(!CreatePipe(&hReadPipe1, &hWritePipe1, &sat, NULL))
{
cout<<("Create Pipe Error!")<<endl;
return 1;
}
//创建管道,它用来做子进程的输入
if(!CreatePipe(&hReadPipe2, &hWritePipe2, &sat, NULL))
{
cout<<"Create Pipe Error!"<<endl;
return 1;
}
startupinfo.cb=sizeof(STARTUPINFO);
//用GetStartupInfo获得当前进程的参数,否则STARTUPINFO参数太多,会让人抓狂
GetStartupInfo(&startupinfo);
startupinfo.hStdInput = hReadPipe2;
startupinfo.hStdError = hWritePipe1;
startupinfo.hStdOutput= hWritePipe1;
//要有STARTF_USESTDHANDLES,否则hStdInput, hStdOutput, hStdError无效
startupinfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
startupinfo.wShowWindow=SW_HIDE;
if(!CreateProcess(NULL, (char*)m_Host.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &startupinfo, &pinfo))
{
cout<<("create process error!")<<endl;
return 1;
}
handle[0] = (HANDLE)_beginthreadex(0, 0, ThreadWritePipe, 0, 0, 0);
handle[1] = (HANDLE)_beginthreadex(0, 0, ThreadReadPipe, 0, 0, 0);
char str[1024] = {'\0'};
bool flag = true;
while(flag)
{
gets(str);
if (str[0] == 'q')
{
flag = !flag;
}
else
{
write_message += str;
}
}
return 0;
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
CloseHandle(hReadPipe1);
CloseHandle(hReadPipe2);
CloseHandle(hWritePipe1);
CloseHandle(hWritePipe2);
return 0;
}
unsigned int __stdcall ThreadWritePipe(PVOID pData)
{
//进程的输入重定向到hReadPipe2,所以从hWritePipe2写入
while (true)
{
if (!write_message.empty())
{
write_message += "\r\n";
if (!WriteFile(hWritePipe2, (LPCVOID)write_message.c_str(), write_message.length(), &byteWrite, NULL))
{
printf("execu ThreadWritePipe\n");
return 1;
}
else
{
write_message = "";
}
}
Sleep(100);
}
return 0;
}