如何在C++中运行另一个应用程序并与之通信,跨平台

use*_*947 0 c++ linux windows cross-platform process

我想从我的C++代码中运行另一个程序.system()返回int,因为每个程序只能返回int到os.但是,我想调用的另一个程序将在我的基本应用程序中生成一个我需要的字符串.如何将其发送到父进程?

这两个应用程序将在同一个文件夹中,所以我认为子应用程序可以将字符串保存到"temp.txt",然后主应用程序可以读取并删除它(这不是性能关键的过程,我将调用另一个进程只是在我的主opengl应用程序中调用打开文件对话框).然而,这是一个有点难看的解决方案,是否有更好的跨平台解决方案?

谢谢

rek*_*ire 5

您可以使用popen(),这将打开一个可以写入和读取数据的过程.AFIK这也是跨平台

// crt_popen.c
/* This program uses _popen and _pclose to receive a 
 * stream of text from a system process.
 */
#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("dir *.c /on /p", "rt")) == NULL)
      exit(1);

        /* Read pipe until end of file. */

   while(!feof(pPipe)) {
      if(fgets(psBuffer, 128, pPipe) != NULL)
         printf(psBuffer);
   }

        /* Close pipe and print return value of pPipe. */

   printf("\nProcess returned %d\n", _pclose(pPipe));

   return 0;
}
Run Code Online (Sandbox Code Playgroud)