2011-12-29 12 views
3

セマフォと_popenの使い方を学びたいと思っています。私には2つのプロセスがあります。C++セマフォと_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; 

プロセス1:

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)); 
} ; 

プロセス2(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);を削除することです(なぜそれがわからないのですか)。

答えて

2

あなたはfgetsを使っていますが、これは改行が見つかるまで読み込みますが、gen.exe isn 'は改行を見つけられるまで読み込みますが、これに

cout<<i; 

::。tが、この変更改行を書い

cout<<i<<endl; 

をそして期待どおりに動作します

+0

非常に非常にありがとうございました^ _ ^。 – Ophelia

関連する問題