【问题标题】:C++ semaphores and _popen usageC++ 信号量和 _popen 用法
【发布时间】:2012-01-30 00:20:21
【问题描述】:

我正在尝试学习如何使用信号量和_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;

流程一:

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 );(我不知道为什么会这样)。我想让它们与信号量一起正常工作,我尝试了很多次,但没有结果:(这个程序有什么问题?

【问题讨论】:

    标签: windows c++-cli ipc semaphore popen


    【解决方案1】:

    您正在使用 fgets,它会一直读取直到找到换行符。但是 gen.exe 没有写换行符。改变这个:

    cout<<i;
    

    到这里:

    cout<<i<<endl;
    

    它按预期工作。

    【讨论】:

    • 非常非常非常感谢^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多