将数据写入管道c++
Write data to pipe C++
我需要做一些像
echo "data" | cat
使用echo "data" | my program
在我的程序中调用cat并将我的标准输入发送给cat标准输入并从cat获得标准输出
我已经fork了进程,关闭了写和读,dup2和execl..所以我可以从中得到标准输出,如果我执行一个execl("/bin/sh", "sh", "-c", "ls -lahtr", NULL),我可以得到文件列表作为输出。
但我不知道如何发送数据,比如发送我从stdin读取的echo数据并发送到execl("/bin/sh", "sh", "-c", "cat", NULL) stdin并返回我的echo字符串。
#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;
}
有了这个代码,我可以发送一些数据到程序,它写在屏幕上,我想知道我如何能得到标准输出和发送到一个变量。谢谢你的帮助ppl.
在fork之前使用两个pipe()调用。这些将是被调用进程的标准输入和标准输出。fork之后,在子进程中,将一个管道的写端设置为stdout(1),将另一个管道的读端设置为stdin(0)。关闭管道中未使用的末端,然后执行进程。
在父进程中,关闭未使用的管道fds。然后,您将拥有一个可以通过read()读取的fd(对应于子进程的标准输出)和一个可以写入的fd(对应于子进程的标准输出)。
相关文章:
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- IPC使用多个管道和分支进程来运行Python程序
- 如何创建函数管道,以便函数一个接一个地运行?
- Gstreamer 管道从命令 lne 到 c 代码
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- 将旧管道转换为现代 openGL 时出现问题
- 如何使用管道在父级和子级之间来回传递文件
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 如何测量管道延迟?
- 我如何使用此程序管道多个命令?C++
- 先进先出:一个进程永远不会从管道读取
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 使用模板而不是虚拟方法的管道模式
- 我可以写入关闭的套接字并强制纠正损坏的管道错误吗?
- 在 Azure DevOps 构建管道中使用英特尔C++编译器为 Linux 环境构建C++代码
- Opencv GStreamer管道在Raspberry Pi 4上不起作用
- 阻塞管道连接命名管道不触发
- GLib-ERROR:为GWakeup创建管道:打开的文件太多
- 向 vulkan 管道添加额外的 UBO 会停止所有几何体渲染
- 在命名管道中发送标准::字符串流