windows - C++ 信号量和 _popen 用法

标签 windows c++-cli ipc semaphore 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;

流程一:

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;

它按预期工作。

关于windows - C++ 信号量和 _popen 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670277/

相关文章:

r - R 中的信号量 (IPC)

c++ - 共享内存进程间通信

windows - 打开命令外壳并执行命令

来自 PID 的 Windows 进程

c++-cli - 我可以在 C++/CLI 中使用原生原始类型吗?

c++-cli - 为什么 Finalize 应该受到保护?

c# - C++ CLI 结构到字节数组

c - 不同.c文件之间的IPC进程间通信

windows - Oracle 无法解决日本操作系统问题

java - 在处理中找不到 android 模式