管道读不出数据
#include <WINDOWS.H>
#include <stdio.h>
DWORD WINAPI ThreadOnputProc(LPVOID lpParameter);
HANDLE hRead1=NULL,hWrite1=NULL;
HANDLE hRead2=NULL,hWrite2=NULL;
CRITICAL_SECTION g_cs;
BOOL threadFlag=FALSE;
void main()
{
InitializeCriticalSection(&g_cs);
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
if(!CreatePipe(&hRead1,&hWrite1,&sa,0) || !CreatePipe(&hRead2,&hWrite2,&sa,0))
{
printf("创建管道失败");
return;
}
char lzCmdline[200];
GetSystemDirectory(lzCmdline,200);
strcat(lzCmdline,"\\cmd.exe");
STARTUPINFO si;
GetStartupInfo(&si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdInput = hRead1;
si.hStdOutput = si.hStdError = hWrite2;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
if(!CreateProcess(lzCmdline,NULL,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
{
printf("创建进程失败");
return ;
}
CreateThread(NULL,0,ThreadOnputProc,NULL,0,0);
char readbuff[1024];
memset(readbuff,0,1024);
DWORD dwTotalAvail;
char writebuff[100];
DWORD dwWrite;
while (TRUE)
{
EnterCriticalSection(&g_cs);
dwTotalAvail=0;
if(threadFlag)
{
//printf("Please Input cmd:\n");
gets(writebuff);
if(!WriteFile(hWrite1, writebuff, sizeof(writebuff), &dwWrite, NULL))
{
printf("写入失败");
return ;
}
threadFlag=FALSE;
}
LeaveCriticalSection(&g_cs);
Sleep(100);
}
CloseHandle(hWrite1);
CloseHandle(hWrite2);
CloseHandle(hRead1);
CloseHandle(hRead2);
}
DWORD WINAPI ThreadOnputProc(LPVOID lpParameter)
{
char readbuff[1024];
DWORD dwRead,dwTotalAvail = 0;
BOOL bRet=FALSE;
while(TRUE)
{
EnterCriticalSection(&g_cs);
if (!threadFlag)
{
memset(readbuff,0,1024);
bRet = PeekNamedPipe(hRead2, NULL, 0, NULL, &dwTotalAvail, NULL);
if (bRet && dwTotalAvail > 0)
{
ReadFile(hRead2,readbuff,1024,&dwRead,NULL);
printf("%s",readbuff);
threadFlag=TRUE;
}
}
LeaveCriticalSection(&g_cs);
Sleep(10);
}
return TRUE;
}