【问题标题】:Execute a process and return its standard output in VC++在 VC++ 中执行一个进程并返回它的标准输出
【发布时间】:2009-07-26 12:20:49
【问题描述】:

执行进程,等待它完成,然后将其标准输出作为字符串返回的最简单方法是什么?

有点像 Perl 中的反引号。

不是在寻找跨平台的东西。我只需要最快的 VC++ 解决方案。

有什么想法吗?

【问题讨论】:

    标签: c++ windows visual-c++ process stdout


    【解决方案1】:

    WinAPI 解决方案:

    您必须使用重定向输入(STARTUPINFO 结构中的 hStdInput 字段)和输出(hStdOutput)到您的管道(参见 CreatePipe)创建进程(参见 CreateProcess),然后从管道中读取(参见 ReadFile)。

    【讨论】:

    【解决方案2】:

    hmm.. MSDN 有这个例子:

    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( "dir *.c /on /p", "rt" )) == NULL )
          exit( 1 );
    
       /* Read pipe until end of file, or an error occurs. */
    
       while(fgets(psBuffer, 128, pPipe))
       {
          printf(psBuffer);
       }
    
    
       /* 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");
       }
    }
    

    看起来很简单。只需要用 C++ 的优点包装它。

    【讨论】:

    • 引用 MSDN -“当在 Windows 程序中使用时,_popen 函数返回一个无效的文件指针,这将导致程序无限期挂起”。如果有任何用处,它将在控制台应用程序中运行。
    • 嗯,控制台应用程序确实是我想要执行的。但是您的评论很重要。也许需要一个更强大的解决方案。
    • 尼尔,实际上,我用“notepad.exe”尝试了上述方法,它只是等到我关闭记事本并返回......
    • 不是这个意思。这意味着您不能在 Windows GUI 应用程序中使用 popen()。您可以使用它从控制台应用程序执行 GUI 应用程序。
    猜你喜欢
    • 2014-02-20
    • 1970-01-01
    • 2011-07-04
    • 2012-07-11
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多