c - 如何将 STDIN 传递给程序并将其输出存储到变量中?C
问题描述
我需要使用 bash 执行文件并将其输出存储到变量中,还需要将字符串s传递给它的标准输入。在 bash 中是这样的:
usr:~$ s | program args
我知道如何调用程序并给他 args:
execvp(program,args);
所以我的问题是给他的标准输入并将输出存储到变量(字符串)!
PS:不能使用system和popen。
解决方案
一些示例代码供您体验。这个执行ls | cat
。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv) {
int fd[2];
int pid;
char* cmd1[2] = {"ls", NULL};
char* cmd2[2] = {"cat", NULL};
int status;
pid = fork();
if (pid == 0) {
pipe(fd);
pid = fork();
if (pid == 0) {
printf("cmd1\n");
dup2(fd[1], 1);
close(fd[0]);
close(fd[1]);
execvp(cmd1[0], cmd1);
printf("Error in execvp\n");
}
else {
dup2(fd[0], 0);
close(fd[0]);
close(fd[1]);
printf("cmd2\n");
execvp(cmd2[0], cmd2);
printf("Error in execvp\n");
}
}
else {
close(fd[0]);
close(fd[1]);
wait(&status);
printf("%d\n", status);
wait(&status);
printf("%d\n", status);
}
}
推荐阅读
- javascript - 带有电子邮件脚本的 gsuite 域
- javascript - 如何在 if 语句上停止 for in 循环
- webpack-4 - Webpack 4优化runtimechunk,runtime.js不能用chunhash命名?
- python - numpy.int64' 对象不可调用
- r - 在 R 中为同一变量绘制两个不同的 x 轴
- sql - BigQuery 将查询限制为 X 行
- python - 如何打印函数返回?
- qt - 桌面应用程序和 GUI 应用程序这两个术语之间是否有任何区别,或者两者的含义相同?
- php - Nginx 总是将 Laravel 路由重定向到默认的根 index.php 页面
- javascript - 从 RxJS 订阅回调更改时,复选框选中的属性不会更新元素