windows管道,该怎么处理

windows管道
本帖最后由 you13fire 于 2012-10-03 10:07:14 编辑
我改写的一个管道通信程序,因为子进程有多个输入输出组合语句,如(scanf,printf,再scanf,printf...),父进程先WriteFile(对应第一个scanf),再ReadFile,发现此时ReadFile阻塞;而一次性WriteFile两个参数时,ReadFile不会阻塞。我的本意是想让VC调试程序的界面调试信息写入到一个txt中。符上代码:
//VS2010  主程序


#include "stdafx.h"

#include "stdafx.h"
#include "Windows.h"
#include "stdio.h"
 
int main(int argc, char* argv[])
{
 SECURITY_ATTRIBUTES sa,sa2; 
 HANDLE hInputRead,hInputWrite; 
 HANDLE hOutputRead,hOutputWrite; 
 
 sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
 sa.lpSecurityDescriptor = NULL; 
 sa.bInheritHandle = TRUE; 
 if (!CreatePipe(&hOutputRead,&hOutputWrite,&sa,0)) 
 { 
  printf("Error On CreatePipe1"); 
  return 1; 
 } 
 
 sa2.nLength = sizeof(SECURITY_ATTRIBUTES); 
 sa2.lpSecurityDescriptor = NULL; 
 sa2.bInheritHandle = TRUE; 
 if (!CreatePipe(&hInputRead,&hInputWrite,&sa2,0)) 
 { 
  printf("Error On CreatePipe2"); 
  return 1; 
 } 
 
 STARTUPINFO si; 
 PROCESS_INFORMATION pi; 
 si.cb = sizeof(STARTUPINFO); 
 GetStartupInfo(&si); 
 si.hStdError = hOutputWrite; 
 si.hStdOutput = hOutputWrite; 
 si.hStdInput = hInputRead;
 si.wShowWindow = SW_SHOW; 
 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 
 
 TCHAR cmd_line[100];
 lstrcpy(cmd_line,TEXT("D:\\test\\Debug\\test.exe"));
 DWORD dwWritten;
 if (!CreateProcess(NULL,cmd_line,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
 {
#ifdef UNICODE
  wprintf(TEXT("Error On CreateProcess")); 
#else
  printf(TEXT("Error On CreateProcess")); 
#endif
  return 1; 
 } 
 
 CloseHandle(hInputRead);
 CloseHandle(hOutputWrite);
 
 char  szInPut[]= ("12\r\n");// 输入//34\r\n23\r\n56\r\n

 if(WriteFile(hInputWrite, szInPut, strlen(szInPut), &dwWritten, NULL))
 printf("write success\n");

 char buffer[32] = {0}; 
 DWORD bytesRead; 

 if(ReadFile(hOutputRead,buffer,31,&bytesRead,NULL))
 printf("read success: %s\n",buffer);

 else
 printf("error\n");

  if(WriteFile(hInputWrite, szInPut, strlen(szInPut), &dwWritten, NULL))
 printf("write success\n");

   if(ReadFile(hOutputRead,buffer,31,&bytesRead,NULL))
 printf("read success: %s\n",buffer);
 else
 printf("error\n");

 
 Sleep(5000);
 CloseHandle(hInputWrite);
 CloseHandle(hOutputRead);
 return 0;
}


/*test.cpp   子进程*/

#include "stdafx.h"
#include "stdio.h"
int main(int argc, char* argv[])
{
int x;
scanf( "%d", &x );
printf("x=%d\n",x);
scanf( "%d", &x );