C ++信号量和_popen使用情况

我正在学习如何使用信号量和_popen。 我有两个进程。

#include <windows.h> #include <stdio.h> #include <conio.h> #include <string> #include <sstream> #include <iostream> #include <process.h> #include <fstream> #using <System.dll> using namespace System; using namespace System::Threading; using namespace std; 

stream程一:

 int main (){ FILE *pPipe; Semaphore^ _pool = gcnew Semaphore( 1, 1, "pool" ); Semaphore^ _eater = gcnew Semaphore(0, 1, "eater" ); char psBuffer[128]; if( (pPipe = _popen( "D:\gen.exe", "rt" )) == NULL ) exit( 1 ); while(!feof( pPipe )){ _eater->WaitOne(); fgets( psBuffer, 128, pPipe ); _pool->Release(); cout<<psBuffer; } printf( "\nProcess returned %d\n", _pclose( pPipe ) ); } ; 

过程二(gen.exe):

 int i=0; Semaphore^ crt = nullptr; crt = Semaphore::OpenExisting( "pool" ); Semaphore^ eat = nullptr; eat = Semaphore::OpenExisting( "eater" ); while(true) { i++; crt->WaitOne(); cout<<i; eat->Release(); } }; 

他们什么都不做。 让他们做某事的唯一方法是删除fgets( psBuffer, 128, pPipe ); (我不知道这是为什么)。 我想使他们与信号灯正常工作,我试了很多次,但没有结果:(这个程序有什么问题?

你正在使用fgets,直到找到一个换行符。 但gen.exe不写一个换行符。 改变这个:

 cout<<i; 

对此:

 cout<<i<<endl; 

它按预期工作。