Windows中的_popen()无法以交互方式工作

时间:2016-10-13 14:10:58

标签: c++ createprocess

我正在使用_popen()创建一个管道来与另一个程序进行通信,我只能执行该程序并且没有源代码访问权限。我已经尝试过MSDN here(_popen示例)和here(CreateProcess和CreateThread示例())中给出的示例。注意代码几乎相同,只是对于_popen我修改了它以写入管道而是如下:

 #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 from parent
Some more Text -> from myprogram
more command from parent
..
..

直到myprogram终止

然而,我得到的是

Some Text -> from myprogram
command entered 

并且它一直在接受命令

你能帮忙吗?

谢谢, FC

0 个答案:

没有答案