C++信号量和 _popen 用法

发布于 2024-12-23 06:21:04 字数 1285 浏览 3 评论 0原文

我正在尝试学习如何使用信号量和 _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 ); (我不知道为什么)。我想让它们与信号量正常工作,我尝试了很多次,但没有结果:(这个程序有什么问题?

I am trying to learn how to use semaphores and _popen. I have two processes.

 #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;

Process one :

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

Process two(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();
  }
}; 

They do nothing. The only way to make them do something is to delete fgets( psBuffer, 128, pPipe );(and i don't know why it is). I want make them to work normally with semaphores, i tried many times, but no result:( What's wrong with this programs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里南柯 2024-12-30 06:21:04

您正在使用 fgets,它会读取直到找到换行符。但 gen.exe 并未写入换行符。将此:更改

cout<<i;

为:

cout<<i<<endl;

它按预期工作。

You're using fgets, which reads until it finds a newline. But gen.exe isn't writing a newline. Change this:

cout<<i;

to this:

cout<<i<<endl;

And it works as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文