【发布时间】:2014-05-06 19:00:43
【问题描述】:
我编写了一个小程序,它应该通过给它一个命令来重定向 cmd.exe 标准输出,并使用管道来获取输入。
程序在使用ipconfig 之类的命令时运行良好,但是当我尝试将tasklist 作为命令传递时,程序就会卡住并且不会得到任何输出。
代码如下:
#include <Windows.h>
#include <tchar.h>
#include <iostream>
#define BUFFSIZE 100000
int wmain(int argc, wchar_t* argv[])
{
HANDLE hReadPipe, hWritePipe;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0) != 0)
{
STARTUPINFO structStartUpInfo;
ZeroMemory(&structStartUpInfo, sizeof(STARTUPINFO));
structStartUpInfo.cb = sizeof(STARTUPINFO);
structStartUpInfo.wShowWindow = SW_HIDE;
structStartUpInfo.hStdInput = hReadPipe;
structStartUpInfo.hStdOutput = hWritePipe;
structStartUpInfo.dwFlags = STARTF_USESTDHANDLES;
PROCESS_INFORMATION structProcInf;
ZeroMemory(&structProcInf, sizeof(PROCESS_INFORMATION));
if (CreateProcess(NULL, L"tasklist", NULL, NULL, TRUE, NORM AL_PRIORITY_CLASS, NULL, NULL, &structStartUpInfo, &structProcInf) != 0)
{
WaitForSingleObject(structProcInf.hProcess, INFINITE);
CHAR output[BUFFSIZE];
DWORD wdByteToRead = BUFFSIZE;
DWORD dwByteread;
ReadFile(hReadPipe, output, wdByteToRead, &dwByteread, NULL);
std::string final = output;
final = final.substr(0, dwByteread);
std::cout << final.c_str();
}
}
return 0;
我该如何解决这个问题?
【问题讨论】: