c - 在 C 中管道两个 shell 命令
问题描述
我正在尝试grep -o colour colourfile.txt | wc -w > newfile.txt
通过 C 中的程序执行,而不是使用命令行。
这是我到目前为止所拥有的:
#include <stdlib.h>
#include <unistd.h>
int main (void) {
int fd[2];
pipe(fd);
if (fork()) {
// Child process
dup2(fd[0], 0); // wc reads from the pipe
close(fd[0]);
close(fd[1]);
execlp("wc", "wc", "-w", ">", "newfile.txt", NULL);
} else {
// Parent process
dup2(fd[1], 1); // grep writes to the pipe
close(fd[0]);
close(fd[1]);
execlp("grep", "grep", "-o", "colour", "colourfile.txt", NULL);
}
exit(EXIT_FAILURE);
}
解决方案
if (fork()) {
表示parent process
不是child process
,请参阅http://man7.org/linux/man-pages/man2/fork.2.html- 你应该处理
>
类似的|
使用open()
以下code
可以工作:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main (void) {
int pipefd[2];
pipe(pipefd);
if (fork()) {
// Child process
dup2(pipefd[0], 0); // wc reads from the pipe
close(pipefd[0]);
close(pipefd[1]);
int fd = open("newfile.txt", O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
dup2(fd, 1);
close(fd);
execlp("wc", "wc", "-w", NULL);
} else {
// Parent process
dup2(pipefd[1], 1); // grep writes to the pipe
close(pipefd[0]);
close(pipefd[1]);
execlp("grep", "grep", "-o", "colour", "colourfile.txt", NULL);
}
exit(EXIT_FAILURE);
}
推荐阅读
- python - 在 3D MatplotLib Scatterplot 中绘制超平面
- java - 如何在 Eclipse 中从 rubenlagus 导入 Telegram Bot API
- r - 根据对 Shiny 中上一个菜单的响应显示不同的选择菜单
- mysql - 如何返回第二个表中为空的客户和附加信息
- windows - OpenSSL 致命错误 LNK1112:模块机器类型“x86”与目标机器类型“x64”冲突
- amazon-web-services - AWS S3如何将文件夹设为今天的日期
- powershell - 在读取 CSV 和输出 TXT 文件的 PowerShell 脚本中需要我的错误/遗漏的 ID
- python-3.x - 为什么 python asyncio 代码卡在第一个并发任务上?
- r - 如何使用`officer`在powerpoint中设置对象的边框颜色?
- php - 如何使用 Google Places API 将 Google 评论嵌入 HTML 或 PHP