将数据发送到另一个C ++程序

时间:2012-06-25 19:54:58

标签: c++ inter-process-communicat

是否可以将数据发送到另一个C ++程序 而无法修改其他程序 (因为有些人似乎错过了这个重要限制)?如果是这样,你会怎么做?我当前的方法涉及创建一个临时文件并以文件名作为参数启动另一个程序。唯一的问题是,这会留下一堆临时文件,以便以后清理,这是不需要的。

编辑:此外,提升 不是 一个选项。

2 个答案:

答案 0 :(得分:4)

显然,如果第二个程序支持它,那么构建一个到stdin的管道是可行的方法。正如弗雷德在评论中提到的,如果没有提供命名文件,或者使用-作为文件名,许多程序会读取标准输入。

如果必须获取文件名,并且您使用的是Linux,请尝试以下操作:创建管道,并在命令行上传递/dev/fd/<fd-number>/proc/self/fd/<fd-number>。< / p>

举例来说,这是hello-world 2.0:

#include <string>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main () {

  int pfd[2];
  int rc;

  if( pipe(pfd) < 0 ) {
    perror("pipe");
    return 1;
  }

  switch(fork()) {
  case -1: // Error
    perror("fork");
    return 1;

  case 0: { // Child
    // Close the writing end of the pipe
    close(pfd[1]);

    // Create a filename that refers to reading end of pipe
    std::ostringstream path;
    path << "/proc/self/fd/" << pfd[0];

    // Invoke the subject program. "cat" will do nicely.
    execlp("/bin/cat", "cat", path.str().c_str(), (char*)0);

    // If we got here, then something went wrong, then execlp failed
    perror("exec");
    return 1;
  }

  default: // Parent
    // Close the reading end.
    close(pfd[0]);

    // Write to the pipe. Since "cat" is on the other end, expect to
    // see "Hello, world" on your screen.
    if (write(pfd[1], "Hello, world\n", 13) != 13)
      perror("write");

    // Signal "cat" that we are done writing
    close(pfd[1]);

    // Wait for "cat" to finish its business
    if( wait(0) < 0)
      perror("wait");

    // Everything's okay
    return 0;
  }
}

答案 1 :(得分:1)

你可以使用套接字。听起来两个应用程序都在同一个主机上,所以你只需将对等体识别为localhost:portA和localhost:port B.如果你这样做,你最终可以毕业做网络IO。没有临时文件,没有神秘的解析错误或文件删除。 TCP保证数据包传输并保证它们将被正确订购。

所以是的,我会考虑创建一个同步套接字服务器(如果您预计会有大量的对等体,则使用异步)。与管道导向的IPC相比的一个好处是TCP套接字是完全通用的。管道根据您所使用的系统而有很大差异(考虑Windows命名管道与隐式和显式POSIX管道 - >非常不同)。