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

标签 c++ linux windows cross-platform process

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

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

谢谢

最佳答案

你可以使用 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;
}

关于c++ - 如何在 C++ 中运行另一个应用程序并与之通信,跨平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978162/

相关文章:

Linux:我怎么知道导出设备节点的模块?

windows - 处理多个鼠标

c - 为什么许多窗口的窗口创建速度很慢?可以更快吗?

c++ - 不匹配 'operator* in ' (1.0e + 0 - ((double)u)) * bezPoints[i][(j + 1)]'

c++ - 循环遍历 Lua 表格中的表格

c++ - 在 os x 10.9.4 上安装 allegro 4?

linux - ZSH 中的文件完成优先级

linux - sar %ifutil 和 nicstat %Util 有什么区别?

Windows 8 支持 d3d8.dll?

c++ - GCC 产生隐藏的删除运算符调用,尽管构造函数被标记为 noexcept