关于PeekNamedPipe的问题??
以下小弟使用创建子进程,或对其输出重定向
但是有点问题
Sleep(500);/////////************问题点************
当初没加这句话
导致cntReadedChar 是零,也就使得szMessage 成了只有[\0]的数组
没有得到子进程的输出
谁讲讲这是为什么?
{
SECURITY_ATTRIBUTES lsa;
STARTUPINFO si;
PROCESS_INFORMATION pi;
HANDLE hReadPipe, hWritePipe;
char szOutput[DEFAULT_BUFFER_LEN+10];
DWORD cntReadedChar=0;
lsa.nLength = sizeof(SECURITY_ATTRIBUTES);
lsa.lpSecurityDescriptor = NULL;
lsa.bInheritHandle = TRUE;
if(!CreatePipe(&hReadPipe, &hWritePipe, &lsa, 0))
{
printf("CreateProcess error!\n");
return FALSE;
}
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe; //use to redirect
if(!CreateProcess(NULL,"core", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
printf("CreateProcess error!\n");
return FALSE;
}
Sleep(500);/////////************问题点************
if(!PeekNamedPipe(hReadPipe, szOutput, 1, &cntReadedChar, NULL, 0)) //CONFIRM IF HAVE SOME OTHER OUTPUT STRING
printf("no output!!\n");
printf("%d\n",cntReadedChar);
if(cntReadedChar) //HAVE UN-READED THING
{
if(!ReadFile(hReadPipe, szOutput, DEFAULT_BUFFER_LEN, &cntReadedChar, NULL))
szOutput[cntReadedChar] = '\0';
}
else
if(WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0)
Sleep(1000);
strcpy(szMessage , szOutput);
printf("%s\n",szOutput);
CloseHandle(hReadPipe);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(hWritePipe);
return TRUE;
}