管道程序.很多书上的程序是错误的!

本文通过两个示例展示了如何在Windows环境下使用匿名管道进行进程间通信。第一个示例创建了一个父进程与子进程间的管道,并演示了如何从子进程中读取输出。第二个示例则是一个无限循环的程序,不断向管道中输出信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 #include "stdafx.h"
#include "windows.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 STARTUPINFO myStartup;
 PROCESS_INFORMATION myInfo;
 BOOL bReturn;
 char readBuf[100];
 DWORD bytesRead = 0;
  HANDLE hRead,hWrite,hTmp;
 SECURITY_ATTRIBUTES ss;
 ss.nLength = sizeof( SECURITY_ATTRIBUTES );
 ss.bInheritHandle = TRUE;
 ss.lpSecurityDescriptor = NULL;
 //create Anonymous Pipe
 if( CreatePipe( &hRead , &hWrite , &ss , 0 ) )
  cout<<"Pipe Created OK"<<endl;
 else
  cout<<"Pipe Creation Error:"<<GetLastError()<<endl;
 hTmp = GetStdHandle( STD_OUTPUT_HANDLE );
 SetStdHandle( STD_OUTPUT_HANDLE , hWrite );
 GetStartupInfo( &myStartup );

//很多书上没有写这段代码,导致下面的进程并没有把输出写到指定的管道
 myStartup.hStdError = hWrite;
 myStartup.hStdOutput = hWrite;
 myStartup.wShowWindow = SW_HIDE;
 myStartup.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
 //get server address
 bReturn = CreateProcess( _T("..//debug//logger.exe") ,NULL , NULL , NULL , TRUE ,
  NULL , NULL , NULL , &myStartup , &myInfo );
 SetStdHandle( STD_OUTPUT_HANDLE , hTmp );
 CloseHandle( hWrite );
 while( ReadFile( hRead , readBuf , 100 , &bytesRead , NULL ))
 {
  readBuf[bytesRead] = '/0';
  printf( "Read %d bytes from pipe[%s]" , bytesRead , readBuf );    
 }
 if( GetLastError() == ERROR_BROKEN_PIPE )
  printf( "Pipe Closed by child process/n" );
 else
  printf( "Read Error:%d/n", GetLastError() );
 CloseHandle( myInfo.hProcess );
  CloseHandle( myInfo.hThread );
 int iii;
 cin>>iii;
 return 0;
}
//////////////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "windows.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 int i = 0;
 for( ;; )
 {
  //printf( "Logging %d/n", i );
  cout<<flush<<"Output Line:"<<i<<endl;
  cerr<<flush<<"Error line"<<i<<endl;
  _flushall();

 }
 return 1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值