将数据发送到另一个C++程序
Send data to another C++ program
是否可以将数据发送到另一个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 管道 ->非常不同)。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口