C++ _Windows中的popen()无法交互工作
我正在使用_popen()创建一个管道,以便与另一个程序进行通信,我只能执行该程序,并且无法访问该程序的源代码。我尝试了MSDN(_popenexample)和(CreateProcess和CreateThread example())中给出的示例。请注意,除了_popen之外,代码几乎相同,我将其修改为写入管道,如下所示:C++ _Windows中的popen()无法交互工作,c++,createprocess,C++,Createprocess,我正在使用_popen()创建一个管道,以便与另一个程序进行通信,我只能执行该程序,并且无法访问该程序的源代码。我尝试了MSDN(_popenexample)和(CreateProcess和CreateThread example())中给出的示例。请注意,除了_popen之外,代码几乎相同,我将其修改为写入管道,如下所示: #include <stdio.h> #include <stdlib.h> int main( void ) {
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char psBuffer[128];
FILE *pPipe;
/* Run DIR so that it writes its output to a pipe. Open this
* pipe with read text attribute so that we can read it
* like a text file.
*/
if( (pPipe = _popen( "myprogram", "wt" )) == NULL )
exit( 1 );
/* Read pipe until end of file, or an error occurs. */
while(!feof( pPipe)))
{
char cmd[32]="";
while(fgets(psBuffer, 128, pPipe))
{
printf(psBuffer);
}
scanf("%s", cmd);
fprintf(pPipe,"%s",cmd);
}
/* Close pipe and print return value of pPipe. */
if (feof( pPipe))
{
printf( "\nProcess returned %d\n", _pclose( pPipe ) );
}
else
{
printf( "Error: Failed to read the pipe to the end.\n");
}
}
直到我的程序终止
然而,我得到的是
Some Text -> from myprogram
command entered
它永远接受命令
你能帮忙吗
谢谢,
FC此
printf(psBuffer)
看起来不正确,实际上没有更改它。我们在MSDN上使用过它,所以我并不怀疑它。fgets
是一个阻塞调用,在找到换行符、缓冲区已满或流结束之前一直读取。因此,您的内部while
循环一直运行到myprogram终止,而从不执行scanf
call在结束之前在外部循环中。如果您只希望myprogram中有一行文本,那么您最好去掉内部while
。否则您必须找到一种方法来判断myprogram已完成编写并且可以接受输入。@KarstenKoop好的。因此,即使我删除while,fgets
(我假设)因为我收到一条我放在外循环末尾的消息。但是我猜输入没有到达pPipe,或者更确切地说,fgets
仍然阻塞管道。我尝试使用fscanf
,但是我的输入没有到达pPipe。这printf(psBuffer)
看起来不正确,实际上没有更改它。我们在MSDN上使用过它,所以我并不怀疑它。fgets
是一个阻塞调用,在找到换行符、缓冲区已满或流结束之前一直读取。因此,您的内部while
循环一直运行到myprogram终止,而从不执行scanf
call在结束之前在外部循环中。如果您只希望myprogram中有一行文本,那么您最好去掉内部while
。否则您必须找到一种方法来判断myprogram已完成编写并且可以接受输入。@KarstenKoop好的。因此,即使我删除while,fgets
(我假设)因为我收到一条我放在外循环末尾的消息。但是我猜输入没有到达pPipe,或者更确切地说,fgets
仍然阻塞管道。我尝试使用fscanf
,但是我的输入没有到达pPipe。
Some Text -> from myprogram
command entered