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

标签 c++ inter-process-communicat

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

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

最佳答案

显然,如果第二个程序支持的话,构建一个到标准输入的管道是可行的方法。正如 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, 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;
  }
}

关于c++ - 将数据发送到另一个 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196379/

相关文章:

c++ - 根据减法运算的结果排序

c++ - 我们不能在 view::chunk 之前惰性地执行 view::filter 吗?

c++ - 在 cout 中打印 getline() 字符串时出现奇怪的错误

java - Java 中对 IPC 的 RMI 支持

c# - 在 Windows 服务中创建时找不到命名事件

c++ - 如何知道数组的值是否由零组成?

c++ - 如果 count() 是 constexpr 函数,为什么 std::array<int, count()> 不能编译?

objective-c - 在 XPC 服务守护进程中查看可用的字典?

linux - 如果刷新映射文件时进程崩溃会发生什么?