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;
进程一:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用 fgets,它会读取直到找到换行符。但 gen.exe 并未写入换行符。将此:更改
为:
它按预期工作。
You're using fgets, which reads until it finds a newline. But gen.exe isn't writing a newline. Change this:
to this:
And it works as expected.