【发布时间】:2012-01-28 01:16:54
【问题描述】:
我需要做类似的事情
echo "data" | cat
使用
echo "data" | my program
在我的程序内部调用 cat 并将我的标准输入发送到 cat 标准输入并从 cat 获取标准输出。
我已经 fork 进程,关闭写入和读取,dup2 并执行。 所以我可以从中获取标准输出,如果我执行一个 execl("/bin/sh", "sh", "-c", "ls -lahtr", NULL) 我可以获得文件列表作为输出。
但我不知道如何发送数据,例如发送从标准输入读取的回显数据并发送到 execl("/bin/sh", "sh", "-c", "cat" , NULL) 标准输入并返回我的回显字符串。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
int ficheiro_fd;
int pipe_fd[2];
char buffer[20];
int num_bytes;
pipe(pipe_fd);
switch ( fork() ) {
case -1:
exit(1);
case 0:
close(pipe_fd[1]);
dup2(pipe_fd[0], 0);
execlp("/usr/bin/base64"," ", NULL);
break;
default:
close(pipe_fd[0]);
//ficheiro_fd = open("output.txt", O_RDONLY);
while ((num_bytes = read(fileno(stdin), buffer, 1)) > 0){
write(pipe_fd[1], buffer, num_bytes);
}
close(pipe_fd[1]);
wait((int*)getpid());
}
return 0;
}
使用此代码,我可以将一些数据发送到程序并在屏幕上写入,我想知道如何获取标准输出并发送到一个变量。 谢谢大家的帮助。
【问题讨论】:
-
看起来你在做一些完全没用的事情。请显示一些代码。
-
你能分享你的代码吗?你的问题有点复杂。一般来说,管道只有一种方式,一个进程读取而另一个进程写入,您不能通过同一管道将数据从读取器发送回写入器。所以你可以做回声数据|你的程序 | cat ... 会将您程序的标准输出传递给 cat 的标准输入...
-
您好,我分享了代码,我需要的原因是我要通过套接字发送一个命令,我需要在另一端处理我的输入并获得返回。