【发布时间】:2019-07-28 16:05:39
【问题描述】:
我正在尝试通过 C 中的程序执行 grep -o colour colourfile.txt | wc -w > newfile.txt,而不是使用命令行。
这是我目前所拥有的:
#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);
}
【问题讨论】:
-
你没有具体提到你的问题在哪里,什么不起作用等等。
-
>是对 shell 的指令,而不是wc的参数;它告诉 shell 在exec*-family 调用之前打开newfile.txt进行写入,并告诉dup2()将其转到FD 1。因此,您也需要自己实现该逻辑。 -
就像管道运算符(
|)是由shell实现的,输出重定向运算符>也是如此。要模拟您提供的 shell 命令,您的程序也必须实现后者。 -
建议了解函数:
popen()及其应用