因此,如果您运行下面的代码,它将int retVal = WaitForSingleObject( processInfo.hProcess, INFINITE);
永远停止。但是当我运行“ipconfig”或“ping 192.168.0.1”而不是“systeminfo”时,代码运行良好。我想知道如何解决这个问题以及导致这个问题的原因是什么?
#include <windows.h>
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpComLine,
int nCmdShow)
{
SECURITY_ATTRIBUTES secAttr;
HANDLE hRead,hWrite;
secAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
secAttr.lpSecurityDescriptor = NULL;
secAttr.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&secAttr,0))
{
return FALSE;
}
char command[1024];
strcpy(command, "systeminfo");
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInfo;
startupInfo.cb = sizeof(STARTUPINFO);
GetStartupInfo(&startupInfo);
startupInfo.hStdError = hWrite;
startupInfo.hStdOutput = hWrite;
startupInfo.hStdInput = hRead;
startupInfo.lpTitle = "CMD";
startupInfo.wShowWindow = SW_HIDE;
startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
if (!CreateProcess(NULL, command,NULL,NULL,TRUE,NULL,NULL,NULL,&startupInfo,&processInfo))
{
MessageBox(NULL, "Error", NULL, MB_OK);
CloseHandle(hWrite);
CloseHandle(hRead);
return FALSE;
}
char buffer[1024] = {0};
DWORD bytesRead;
int retVal = WaitForSingleObject( processInfo.hProcess, INFINITE);
if (retVal == WAIT_FAILED)
MessageBox(NULL, "WAIT_FAILED", NULL, MB_OK);
else if (retVal == WAIT_TIMEOUT)
MessageBox(NULL, "WAIT_TIMEOUT", NULL, MB_OK);
ReadFile(hRead,buffer,1024,&bytesRead,NULL);
MessageBox(NULL, buffer, NULL, MB_OK);
CloseHandle(hWrite);
CloseHandle(hRead);
return 0;
}