我正在尝试执行以下命令,
ls | grep "SOMETHING"
用c编程语言编写。任何人都可以帮助我。
我想分叉一个孩子,我将使用execlp运行ls命令。 在父级中,我得到了孩子和grep的输出(再次使用execlp)。
不可能吗?
答案 0 :(得分:8)
我终于找到了它的代码。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
execlp("ls", "ls", NULL);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
execlp("grep", "SOMETHING", NULL);
}
return 0;
}
答案 1 :(得分:3)
管道只是从一个标准输出读取并写入另一个标准输出
是否要实现具有管道功能的shell解释器?
首先,你需要一个shell解析器来解析commond
然后,您将拥有管道功能
...