我正在尝试执行以下命令,
ls | grep“某事”
用c编程语言。谁能帮我解决这个问题。
我想 fork 一个 child ,我将在其中使用 execlp 运行 ls 命令。 在父级中,我得到子级和 grep 的输出(再次使用 execlp)。
这不可能吗?
最佳答案
我终于找到了它的代码。
#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;
}
关于c - 在 Linux 中使用 c 实现管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166721/