C++ 中的子进程命令

Ric*_*ard 6 c++ subprocess pipe

我有两个 C++ 程序:Program1 和 Program2。我想要做的是让 Program1 运行其算法来计算它需要的任何内容,然后将所有计算出的信息通过管道传输到 Program2 中,让它使用 Program1 的输出运行其算法。

如果我可以通过管道传递信息并关闭 Program1 而不必先等待 Program2 完成,那就太好了。它类似于python 中的subprocess.call()。

ran*_*ame 3

你会想做一些类似的事情:

#include <unistd.h>

int main () {
  // Do stuff for program1
  int pipefds[2];
  if (pipe (pipefds))
    throw 1;
  // Use ``write'' to send binary data to pipefds[0]
  dup2 (pipefds[1], 0);
  execl (/* Put the program2 arguments you want here. */);
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

有了这个,您所需要的就是让program2从stdin中读取所有必要的数据,然后您就完成了。