是否可以将数据发送到另一个 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/