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

Send data to another C++ program

本文关键字:另一个 C++ 程序 数据      更新时间:2023-10-16

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

编辑:此外,提升不是一种选择。

显然,如果第二个程序支持,那么构建通往 stdin 的管道是要走的路。正如Fred在评论中提到的,如果没有提供命名文件,或者-用作文件名,许多程序都会读取stdin。

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

举个例子,这里是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, worldn", 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;
  }
}

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

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

相关文章: